我有两个独立的 View Controller 。
在 ViewController1
,我有一个CollectionView1
和一个运行良好的电池。我使用 storyboard
设置单元格与 ReuseIdentifier "Cell1"
.
在 ViewController2
,我还有一个CollectionView2
和一个工作正常的不同细胞。我还使用 storyboard
设置单元格与 ReuseIdentifier "Cell2"
.
两个单元格都有自定义单元格类别,UserCell1
和UserCell2
,并在其单独的 CollectionViews
内正常工作.
现在,对于 CollectionView2
中的第二个单元格,我想使用第一个 Collection View (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 中而不是 Storyboard中定义每个单元格,这将帮助您通过从代码注册它们来重用任何 Collection View 中的两个单元格,您可以在此处查看示例:
How to load custom cell ( xib) in UICollectionView cell using swift
如果由于某种原因需要在storyboard中定义cell,那么你需要在每个collectionView2中声明两个原型(prototype)cell
请参阅以下屏幕,我们有一个 Collection View ,其项目数 = 2,我们应该为每个单元格提供唯一的 ReuseIdentifier
关于swift - UICollectionView 具有多个不同的单元格,在其他 CollectionView 中注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284199/