使用多个ViewController问题相同的CollectionView单元格
当我尝试在多个ViewController中使用同一单元格时,我会遇到致命错误:当我尝试填充单元格中的标签时,意外地发现了零,同时隐式解开可选的价值错误。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CategoryCollectionViewCell
cell?.categoryLabel.text = "label"
cell!.contentView.layer.cornerRadius = 7.5
return cell!
}
When I try to use the same cell in more than one viewcontroller, I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value error when I try to fill in the labels in the cell.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CategoryCollectionViewCell
cell?.categoryLabel.text = "label"
cell!.contentView.layer.cornerRadius = 7.5
return cell!
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将收集单元设计为故事板中的原型时:
该单元格属于 该收集视图 and>该收集仅视图。您不能将其与其他收集视图或控制器一起使用。
如果要设计可以在多个控制器 /收集视图中使用的单元格,则需要将其设计为XIB或仅代码。
When you design a collection view cell as a prototype in Storyboard:
That cell belongs to that collection view and that collection view only. You cannot use it with other collection views or controllers.
If you want to design a cell that can be used in multiple controllers / collection views, you need to either design it as a XIB or code-only.