尝试注册不是UICollectionViewCell的子类的单元类。咦?

时间:2014-12-01 08:08:25

标签: swift uicollectionviewcell

我正在尝试使用部分创建我的第一个UICollectionView。

场景:带有UICollectionView成员的UIViewController。

目标:注册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 here enter image description here

  

... reason:'尝试注册一个不是子类的单元类   UICollectionViewCell(UICollectionReusableView)'

问题:我在这里看不到任何错误,标题被视为单元格,但标记为不是真正的UICollectionReusableView。为什么?

<小时/> 当我注释掉注册时:

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


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

    }

...我的应用程序(减去尚未编码的标题)工作。 ---我不需要注册单元格吗?

2 个答案:

答案 0 :(得分:2)

如果原型是在InterfaceBuilder中设计的,则无需注册该类。只需在那里给它一个重用标识符。

答案 1 :(得分:2)

我也收到此错误:

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