【问题标题】:Why do I have to use .self to reference the type object in swift?为什么我必须使用 .self 来快速引用类型对象?
【发布时间】:2021-04-09 05:16:07
【问题描述】:

我正在配置一个集合视图以使用我自己的自定义单元格但是,我一直想知道为什么我必须在 collectionview.register(any class, forCellReuseIdentifier) 内的单元格类中包含 .self。

也许我的 OOP 技能只是在这里缺乏,但为什么 .self 会引用类型对象呢?为什么需要知道类型?任何帮助将不胜感激。

    func configureCollectionView() {
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewLayout())
        view.addSubview(collectionView)
        collectionView.backgroundColor = .systemPink
        //collectionView.register(FollowerCell.self, forCellWithReuseIdentifier: FollowerCell.reuseID)
        collectionView.register(FollowerCell, forCellWithReuseIdentifier: FollowerCell.reuseID)
    }
class FollowerCell: UICollectionViewCell {
    static let reuseID = "FollowerCell"
    
    let avatarImageView = GFAvatarImageView(frame: .zero)
    let userNameLabel = GFTitleLabel(textAlignment: .center, fontSize: 16)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configure()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

【问题讨论】:

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

这就是 Swift 的工作方式。当你被要求传递一个 type 作为参数时,你不能传递类型的裸名;你把名字加上.self

您只需要接受语言就是这样运作的。这就像为什么法语中的“yes”、“oui”是这样的;你不问为什么,你只是学习它并使用它。或者为什么在板球比赛中边界命中 4 分;你不要问为什么,这只是游戏规则。

【讨论】:

  • 非常感谢您的回复!我想我只是有点困惑,为什么他们要求一种类型,而它专门只是要求上课。我的新手大脑只是想“哦,他们想要我的细胞课程,就是这样”。但我猜一个类是一个命名类型,每个单元格都需要知道是什么类型?这有点正确吗?谢谢!
  • 您告诉表格视图在需要新单元格时应该实例化哪类单元格。所以它在问“什么课?”因此,您的答案必须采用ClassName.self 的形式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2019-03-31
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多