【问题标题】:Collection view crashing on cell.viewWithTag(100)集合视图在 cell.viewWithTag(100) 上崩溃
【发布时间】:2016-03-07 14:45:04
【问题描述】:

我正在尝试按照this tutorial 中的描述实现集合 vie

它在下一行崩溃

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

fatal error: unexpectedly found nil while unwrapping an Optional value

我的 imageView 是可重用单元格的唯一孩子,并且 imageView 的标签为100

方法的其余部分

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
}

【问题讨论】:

  • 推荐你使用标签的教程(而不是告诉你为什么这是一个坏主意)是一个糟糕的教程。你是怎么检查标签是 100 的?
  • 在属性检查器的界面生成器中设置
  • 你说是100,我问你怎么知道是100,你在运行时检查了吗?您的错误表明它实际上不是 100。也许图像视图甚至不是子视图...
  • 是的,抱歉误读了您的评论。如果有帮助,我添加了 2 个屏幕截图。
  • 您需要在运行时调试和检查真相——可能您正在编辑标签或从 NIB / 故事板以外的其他东西实例化单元格

标签: ios swift uiimageview uicollectionview


【解决方案1】:

那个错误告诉你你正在用“!”强制解包的东西。实际上是零。

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

相反,请使用“if let”可选绑定、警卫语句或其他一些方法,如果可选包含 nil,您可以优雅地失败。

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

查看我创建的涵盖该主题的主题:

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

【讨论】:

    【解决方案2】:

    您不应该通过标签访问单元格图像。创建一个自定义单元格类并为 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多