首页 文章

Swift - 无法出现类型的视图:带标识符的UICollectionElementKindCell

提问于
浏览
10

尝试加载UICollectionView时收到此错误消息 .

2015-07-23 16:16:09.754 XXXXX [24780:465607]由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无法使类型的视图出列:具有标识符CollectionViewCell的UICollectionElementKindCell - 必须注册一个nib或类用于标识符或连接故事板中的原型单元格'第一个抛出调用堆栈:

我的代码

@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

    }

我已经在storyboard检查器中声明了 CollectionViewCell ,但仍然出现错误消息 .

enter image description here

3 回答

  • 0

    看了你的例外后:

    2015-07-23 16:16:09.754 XXXXX [24780:465607] 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无法使类型的视图出列:具有标识符CollectionViewCell的UICollectionElementKindCell - 必须注册一个笔尖或一个标识符的类或连接故事板中的原型单元' First throw call stack:

    最后一部分是最重要的:

    必须为标识符注册一个nib或类,或者在故事板中连接原型单元

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

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

    对于Swift 3:

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

    在你的viewDidLoad()中放入此代码

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

相关问题