我有一个 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)
编辑:
最佳答案
如果单元格是在 Storyboard 中制作的,则不应注册该类(class)。删除该行。确保在 Storyboard 中设置单元格的标识符。仅当您完全用代码创建单元时才注册该类。
关于ios - 尝试访问已注册单元格的成员时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829951/