我有两个单独的视图控制器。
在 中ViewController1
,我有一个CollectionView1
和一个工作正常的单元格。我使用storyboard
with设置单元格ReuseIdentifier "Cell1"
。
在 中ViewController2
,我有另一个CollectionView2
可以正常工作的不同单元格。我也使用storyboard
with设置了单元格ReuseIdentifier "Cell2"
。
两个单元格都有自定义单元格类UserCell1
和UserCell2
,并且在它们单独的CollectionViews
.
现在,对于 中的第二个单元格CollectionView2
,我想使用第一个集合视图中的单元格(ie. IndexPath(row: 1, section: 0))
。
在CollectionView2
,我想要:
IndexPath(row: 0, section: 0) -> "Cell1"
IndexPath(row: 1, section: 0) -> "Cell2"
上ViewController2
,内cellForItemAt
,我已经使用式表示哪个小区试图dequeue
在每一个index
。但是,它告诉我第ViewController
一个单元格没有注册......但同一个单元格正在其家中工作CollectionView
,因此ReuseIdentifier
显然正在工作。
之内 cellForItemAt (numberOfRowsInSection = 2):
if indexPath == IndexPath(row: 0, section: 0) {
guard let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell1", for: indexPath) as? UserCell1 else { return UICollectionViewCell() }
cell1.configure(user: selectedUser)
return cell1
} else if indexPath == IndexPath(row: 1, section: 0) {
guard let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell2", for: indexPath) as? UserCell2 else { return UICollectionViewCell() }
cell2.configure(user: selectedUser)
return cell2
} else {
return UICollectionViewCell()
}
我得到的错误是:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier Cell1 - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
提前致谢!!!!这真让我抓狂 :(
您的代码的最佳做法是在 XIB 中而不是在故事板中定义每个单元格,这将帮助您通过从代码中注册它们来重用任何集合视图中的两个单元格,您可以在此处查看示例:
如何使用swift在UICollectionView单元格中加载自定义单元格(xib)
如果由于某种原因需要在storyboard中定义单元格,则需要在每个collectionView2中声明两个原型单元格
看下面的屏幕,我们有一个集合视图,项目数 = 2,我们应该为每个单元格提供唯一的 ReuseIdentifier
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句