簡體   English   中英

Swift - 無法出現類型的視圖:帶標識符的UICollectionElementKindCell

[英]Swift - could not dequeue a view of kind: UICollectionElementKindCell with identifier

嘗試加載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 ,但仍然出現錯誤消息。

在此輸入圖像描述

看了你的例外后:

2015-07-23 16:16:09.754 XXXXX [24780:465607] *由於未捕獲的異常'NSInternalInconsistencyException'而終止應用程序,原因:'無法使類型的視圖出列:具有標識符CollectionViewCell的UICollectionElementKindCell - 必須注冊一個nib或類用於標識符或連接故事板中的原型單元'* First throw call stack:

最后一部分是最重要的:

必須為標識符注冊一個nib或類,或者在故事板中連接原型單元

這意味着您的集合視圖尚未注冊您的自定義單元格。 要解決此問題,請在viewDidLoad添加以下內容:

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

對於Swift 3:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM