UICollectionViewCell register class fails, but register nib works

会有一股神秘感。 提交于 2019-12-03 05:49:02
vien vu

I see this link Overview Collection View

If the cell class was written in code, the registration is performed using the registerClass: method of UICollectionView. For example: [self.myCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"MYCELL"]; In the event that the cell is contained within an Interface Builder NIB file, the registerNib: method is used instead.

So your collection cell create with nib, you should register with nib. If your cell written totally in code you will need register with class.

Hope this help.

Actually if you register the class in the storyboard and give it a reuse identifier there, then you shouldn't be registering it's class or it's nib in code.

It is not collectionview that is failing here. You custom class contains label which is implicitly unwrapped optional defined as this,

@IBOutlet weak var title: UILabel!

And that is the reason for failure. Where do you instantiate it ? And your datasource methods gets called which is like this,

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! MyCollectionViewCell

    cell.title.text = data[indexPath.row]

    return cell
}

There you are trying to set text to this property title which is nil, which crashes your app.

Initialize your label inside collectionView initWithFrame: method if you use it in code that should should be fixed.

Add this code to your cell subclass when using in code,

class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        let title = UILabel(frame: CGRectZero)
        title.translatesAutoresizingMaskIntoConstraints = false;
        contentView.addSubview(title)
        self.title = title

        title.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true
        title.leftAnchor.constraintEqualToAnchor(contentView.leftAnchor).active = true
        self.backgroundColor = UIColor.redColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

if you define cell from a nib file,system will choose nib file to instantiate the cell. If not define any nib file(totally maintain by code), the cell should be init by the

- initWithStyle:reuseIdentifier:

method. When you use

- dequeueReusableCellWithIdentifier:

the method - awakeFromNib will be called if you use nib to maintain the view; else

- initWithStyle:reuseIdentifier:

will be called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!