Why is UICollectionViewCell's outlet nil?

2019-01-07 04:17发布

问题:

I have created a custom UICollectionViewCell in Interface Builder, binded views on it to the class, and then when I want to use and set a string to the label on the string, tha label has a nil value.

override func viewDidLoad() {
    super.viewDidLoad()

    // Register cell classes
    self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls")
}

override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {

    var cell: LeftMenuCollectionViewCell
    cell = collectionView.dequeueReusableCellWithReuseIdentifier("ls", forIndexPath: indexPath) as LeftMenuCollectionViewCell
    println(cell.label) // <- this is nil, why??
    cell.label.text = "asd"

    return cell
}

And the subclassed cell:

class LeftMenuCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
}

回答1:

I am calling self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls") again. If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard.

If you still have the problem check wether reuseIdentifier is same in dequeueReusableCellWithReuseIdentifier and in storyboard.



回答2:

Just remove this line:

self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls")


回答3:

If you are using xib, make sure that you have added this line of code to your viewdidload.

Objective C:

[self.collectionView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellWithReuseIdentifier:@"MyCellIdentifier"];

Swift:

collectionView.register(UINib(nibName:"MyCell", bundle: nil), forCellWithReuseIdentifier:"MyCellIdentifier")


回答4:

Gotta register that nib guys!

collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "CustomCellId")


回答5:

I had a similar problem, but my mistake was that I didn't delegate CollectionViewCell to be able to change the label text..