[英]Swift - could not dequeue a view of kind: UICollectionElementKindCell with identifier
I got this error message when trying to load UICollectionView. 尝试加载UICollectionView时收到此错误消息。
2015-07-23 16:16:09.754 XXXXX[24780:465607] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier CollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
2015-07-23 16:16:09.754 XXXXX [24780:465607]由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无法使类型的视图出列:具有标识符CollectionViewCell的UICollectionElementKindCell - 必须注册一个nib或类标识符或连接故事板中的原型单元格'
First throw call stack:
第一次抛出调用堆栈:
My code 我的代码
@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
}
I already declared CollectionViewCell
in storyboard inspector but the error message still occur. 我已经在storyboard检查器中声明了
CollectionViewCell
,但仍然出现错误消息。
After taking a look at your exception: 看了你的例外后:
2015-07-23 16:16:09.754 XXXXX[24780:465607] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier CollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' * First throw call stack:
2015-07-23 16:16:09.754 XXXXX [24780:465607] *由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无法使类型的视图出列:具有标识符CollectionViewCell的UICollectionElementKindCell - 必须注册一个nib或类用于标识符或连接故事板中的原型单元'* First throw call stack:
last part is most important: 最后一部分是最重要的:
must register a nib or a class for the identifier or connect a prototype cell in a storyboard
必须为标识符注册一个nib或类,或者在故事板中连接原型单元
Which means that your collection view doesn't have registered your custom cell. 这意味着您的集合视图尚未注册您的自定义单元格。 To resolve this add following in your
viewDidLoad
: 要解决此问题,请在
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.