Swift – 无法将types化的视图出列:带标识符的UICollectionElementKindCell

当试图加载UICollectionView时,我得到了这个错误信息。

2015-07-23 16:16:09.754 XXXXX [24780:465607] *由于未捕获的exception'NSInternalInconsistencyException',原因:'无法出队types视图:具有标识符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 } 

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

在这里输入图像说明

请指教。 谢谢。

看看你的例外之后:

2015-07-23 16:16:09.754 XXXXX [24780:465607] *由于未捕获的exception'NSInternalInconsistencyException',原因:'无法出队types视图:具有标识符CollectionViewCell的UICollectionElementKindCell – 必须注册一个nib或类为标识符或连接故事板中的原型单元格*第一次抛出调用堆栈:

最后一部分是最重要的:

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

这意味着您的collections视图没有注册您的自定义单元格。 要解决这个在您的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")