集合视图崩溃在cell.viewWithTag(100)

时间:2016-03-07 14:45:04

标签: ios swift uiimageview uicollectionview

我正在尝试按this tutorial

中所述实现收集

它崩溃在以下一行

let gelleryImageView: UIImageView = (cell.viewWithTag(100) as! UIImageView)

fatal error: unexpectedly found nil while unwrapping an Optional value

我的imageView是可重复使用单元格的唯一子项,而imageView的标记为100

enter image description here

enter image description here

其余方法

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)

    // Configure the cell
    print(cell.subviews.count)


    let gelleryImageView: UIImageView = (cell.viewWithTag(100) as! UIImageView)

    gelleryImageView.image = images[indexPath.row]

    return cell
}

2 个答案:

答案 0 :(得分:1)

这个错误告诉你,你强行解开的东西"!"实际上是零。

在你习惯选择之前,不要使用强制解包。这很危险。

相反,使用"如果让"可选绑定,或保护语句,或其他一些方法,如果可选项包含nil,则可以使您正常失败。

在您的情况下,很可能没有标记为100的视图,因此它返回nil。如果您没有使用强制解包,那么您就可以

请参阅我创建的关于该主题的主题:

How to deal with "Fatal error: unexpectedly found nil while unwrapping an Optional value."

答案 1 :(得分:0)

您不应该通过标签访问单元格图像。创建一个自定义单元类并为imageView创建一个插座并以这种方式访问​​它。

从viewdidload()中删除行

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

//

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

    cell.galleryImage.image = images[indexPath.row]

    return cell
}
相关问题