ios - 尝试访问已注册单元格的成员时出现运行时错误

标签 ios xcode

我有一个 CollectionView 单元格,其中有一个 ImageView 和一个标签。当我尝试在标签内设置图像或文本时,我的程序因以下错误而崩溃:

fatal error: unexpectedly found nil while unwrapping an Optional value

cell 是继承自 UICollectionViewCell 的自定义类,storyboard 中已经创建并链接了 outlet:

class CustomCell: UICollectionViewCell {

    @IBOutlet var thumbnailImageView: UIImageView!
    @IBOutlet var textLabel: UILabel!
}

我正在设置 imageView:

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

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CustomCell
        cell.thumbnailImageView.image = UIImage(named: "ss")
        return cell
    }

我原本以为图片文件位置有问题所以我把它注释掉并尝试更改标签的文本:

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

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CustomCell
        cell.textLabel.text = "Hello"
        return cell
    }

但这也导致了崩溃。什么会导致自定义单元格正确加载但无法访问其任何成员?

编辑:在 viewdidload 函数中,我像这样注册了我的类:

self.collectionView?.registerClass(CustomCell.self, forCellWithReuseIdentifier: reuseIdentifier)

编辑: enter image description here

最佳答案

如果单元格是在 Storyboard 中制作的,则不应注册该类(class)。删除该行。确保在 Storyboard 中设置单元格的标识符。仅当您完全用代码创建单元时才注册该类。

关于ios - 尝试访问已注册单元格的成员时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829951/

相关文章:

ios - 从另一个文件 Swift/Xcode 调用时函数不会完全执行

iOS In App purchase updatedTransactions : cannot distinguish between new purchase and restore

ios - traitCollection.userInterfaceIdiom 返回 -1

iOS uilabel 滚动时保持在屏幕上

ios - 用\w匹配非英文字符

ios - 如何将大视频保存到相册?

objective-c - UIScrollView:处理动态内容?

ios - 将文本链接添加到 TextView

Xcode 导出 Mac 应用程序,无需开发人员程序

iphone - 从主屏幕重新打开应用程序时如何刷新标签栏内容? (iOS/Xcode)