UICollectionView cell.ViewWithTag returning nil fo

2019-03-01 16:24发布

问题:

This label seems to return nil, even though I have the reuseIdentifier and tag set properly.

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var identifier: String = "CollectionCell"
    var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! UICollectionViewCell

    // Configure the cell


    //save till later, when images are actually present

    //var cellItem1 = hostManager[indexPath.row * 2]

    let label:UILabel = cell.viewWithTag(1) as! UILabel
    return cell

}

The program breaks where the label is set = to the viewWithTag. I have no custom class set for the cell, just the prototype. The tag is set on the storyboard. Getting an error "EXC_BAD_INSTRUCTION...". Any help would be appreciated, Thanks!

回答1:

Try removing this line from viewDidLoad:

self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)


回答2:

I have just created a sample project with your code and for me it works. Although you shouldn't force unwrap.

Make sure you have the correct setup in your storyboard:

Check if your collectionViewCell is setup correctly:

And set the tag of your label:

Here is the sample project