试图注册一个不是UICollectionViewCell子类的单元格类。咦?

问题描述 投票:2回答:2

我正试图创建我的第一个UICollectionView,并使用 部分.

场景:在一个有UICollectionView成员的UIViewController中。 一个带有UICollectionView成员的UIViewController。

目标:注册UICollectionViewCell & UICollectionReusableView(头)单元。 注册UICollectionViewCell & UICollectionReusableView(头)单元格。

问题:我得到了一个运行时错误,即UICollectionViewCell &UICollectionReusableView(头)单元。 我得到了一个运行时错误,即头不是一个UICollectionReusableView。

@IBOutlet weak var gCollectionView: UICollectionView!
@IBOutlet weak var headerView: UICollectionReusableView!


override func viewDidLoad() {
// Cell:
gCollectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: kCellID)


// Header:
gCollectionView.registerClass(UICollectionReusableView.self, forCellWithReuseIdentifier: kHeaderID)
}

enter image description hereenter image description here

...原因:'试图注册一个不是UICollectionViewCell (UICollectionReusableView)的子类的单元格类。

问题。 我看不出这里有什么问题,头被当作单元格处理, 但它被标记为不是一个真正的UICollectionReusableView。 为什么会这样?


当我注销了注册:
 override func viewDidLoad() {
        // Cell:
    //    gCollectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: kCellID)


        // Header:
 //       gCollectionView.registerClass(UICollectionReusableView.self, forCellWithReuseIdentifier: kHeaderID)

    }

...我的应用程序(除去还没有编码的头)就能用了。 --- 我不需要注册单元格吗?

swift uicollectionviewcell
2个回答
3
投票

如果原型是在InterfaceBuilder中设计的,就不需要注册这个类。只要在那里给它一个重用的标识符就可以了。


0
投票

我也收到了这个错误。

Thread 1: Exception: "attempt to register a cell class which is not a subclass of UICollectionViewCell (UICollectionView)"

这是我的集合视图在被破坏时的样子:

fileprivate let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.register(UICollectionView.self, forCellWithReuseIdentifier: "cell")

        return cv
    }()

我的集合视图出了点小问题,我把它改成了这个,然后就可以编译了。

fileprivate let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")

        return cv
    }()

请注意我的错误所在的小改动

  • 我把UICollectionView.self
  • 而应该是UICollectionViewCell.self。
© www.soinside.com 2019 - 2024. All rights reserved.