使用多个ViewController问题相同的CollectionView单元格

发布于 2025-01-17 10:53:43 字数 539 浏览 3 评论 0原文

当我尝试在多个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不羁少年 2025-01-24 10:53:43

当您将收集单元设计为故事板中的原型时:

“在此处输入图像说明”

该单元格属于 该收集视图 and>该收集仅视图。您不能将其与其他收集视图或控制器一起使用。

如果要设计可以在多个控制器 /收集视图中使用的单元格,则需要将其设计为XIB或仅代码。

When you design a collection view cell as a prototype in Storyboard:

enter image description here

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文