首页 > 解决方案 > 无法出列同类视图:带有标识符的 UICollectionElementKindCell - 必须为标识符注册一个 nib 或类

问题描述

这让我发疯。我过去已经整理了几十个集合视图,但是这个拒绝工作。

我的收藏视图单元格有一个 xib,我给它一个标识符“我的单元格”。在我的控制器中,我执行以下操作:

    override func awakeFromNib() {
        super.awakeFromNib()

        myCollectionView.delegate = self
        myCollectionView.dataSource = self

        // Register the collection view cell
        myCollectionView.register(UINib(nibName: "MyCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath) as? MyCell else {
                fatalError("The dequeued cell is not an instance of MyCell.")
        }

        return cell
    }

然而,无论我做什么,Xcode 都会崩溃并给我这个错误:

*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法使类型视图出列:带有标识符 MyCell 的 UICollectionElementKindCell - 必须为标识符注册一个 nib 或类或连接故事板中的原型单元格”

我试过清理构建文件夹,重新启动 Xcode,甚至重新启动我的 Mac,但没有任何效果。

我究竟做错了什么??

标签: iosswiftxcodeswift4swift5

解决方案


我认为你必须检查两件事

  1. 使用这个 myCollectionView.dequeueReusableCell

    ` 覆盖 func awakeFromNib() { super.awakeFromNib()

        myCollectionView.delegate = self
        myCollectionView.dataSource = self
    
        // Register the collection view cell
        myCollectionView.register(UINib(nibName: "MyCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath) as? MyCell else {
                fatalError("The dequeued cell is not an instance of MyCell.")
        }
    
        return cell
    }`
    
  2. 打开 Xib 文件并检查是否设置了可重用标识符

在此处输入图像描述

希望这能解决你的问题,如果不让我知道


推荐阅读