UICollectionView cell.ViewWithTag returning nil for UILabel

陌路散爱 提交于 2019-12-04 05:03:06

问题


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



来源:https://stackoverflow.com/questions/31781933/uicollectionview-cell-viewwithtag-returning-nil-for-uilabel

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