【问题标题】:Swift - could not dequeue a view of kind: UICollectionElementKindCell with identifier斯威夫特 - 无法出列一种视图:带有标识符的 UICollectionElementKindCell
【发布时间】:2015-10-13 10:28:33
【问题描述】:

我在尝试加载 UICollectionView 时收到此错误消息。

2015-07-23 16:16:09.754 XXXXX[24780:465607] 由于以下原因而终止应用程序 未捕获的异常“NSInternalInconsistencyException”,原因:“可能 不出队一种视图: UICollectionElementKindCell 与 标识符 CollectionViewCell - 必须为 标识符或连接故事板中的原型单元'

第一次抛出调用栈:

我的代码

@IBOutlet var collectionView: UICollectionView!

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
        
        cell.backgroundColor = UIColor.blackColor()
        cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
        cell.imageView?.image = UIImage(named: "category")

        return cell

    }

我已经在故事板检查器中声明了CollectionViewCell,但错误消息仍然出现。

【问题讨论】:

  • 我猜你正在单独创建你的 Cell nib,而不是在你的 UICollectionView 中。如果是,则需要先将 nib 文件注册到UICollectionView。使用 UINib *cellNib = [UINib nibWithNibName:@"CollectionViewCell" bundle:nil]; [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"CollectionViewCell"];

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

查看您的异常后:

2015-07-23 16:16:09.754 XXXXX[24780:465607] * 由于以下原因而终止应用程序 未捕获的异常“NSInternalInconsistencyException”,原因:“可能 不出队一种视图: UICollectionElementKindCell 与 标识符 CollectionViewCell - 必须为 标识符或连接故事板中的原型单元'*第一次抛出 调用栈:

最后一部分是最重要的:

必须为 标识符或连接情节提要中的原型单元

这意味着您的集合视图没有注册您的自定义单元格。要解决此问题,请在您的 viewDidLoad 中添加以下内容:

var nib = UINib(nibName: "UICollectionElementKindCell", bundle:nil)
self.collectionView.registerNib(nib, forCellReuseIdentifier: "CollectionViewCell")

【讨论】:

  • 谢谢。我的问题是我没有注册我的 Nib,而是注册了这个类: self.collectionView!.registerClass(customCollectionCell.self, forCellWithReuseIdentifier: "Cell") 但是你的代码可以工作。
【解决方案2】:

对于 Swift 3:

collectionView.register(YourCustomCellClass.self, forCellWithReuseIdentifier: "cell")

【讨论】:

    【解决方案3】:

    在你的 viewDidLoad() 中输入这段代码

    collectionView.registerClass(YourCustomCellClass.self, forCellWithReuseIdentifier: "cell")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2017-03-24
      • 2020-05-27
      相关资源
      最近更新 更多