swift - UICollectionView 具有多个不同的单元格,在其他 CollectionView 中注册

标签 swift uicollectionview uicollectionviewcell uicollectionviewlayout uicollectionviewflowlayout

我有两个独立的 View Controller 。

ViewController1 ,我有一个CollectionView1和一个运行良好的电池。我使用 storyboard 设置单元格与 ReuseIdentifier "Cell1" .

ViewController2 ,我还有一个CollectionView2和一个工作正常的不同细胞。我还使用 storyboard 设置单元格与 ReuseIdentifier "Cell2" .

两个单元格都有自定义单元格类别,UserCell1UserCell2 ,并在其单独的 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

enter image description here

关于swift - UICollectionView 具有多个不同的单元格,在其他 CollectionView 中注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284199/

相关文章:

ios - 为任何实现多个协议(protocol)的对象定义一个 Swift 类型别名

ios - 以编程方式创建 UICollectionView

ios - 如何实现这种类型的 Collection View 网格

ios - 使用时标签显示文本效果不佳[cell setNeedsDisplay]

ios - uitableViewCell.rounded Corners 不会立即显示

ios - 如何为某些用户隐藏栏按钮项目

c# - Xamarin CollectionView 在滚动时突出显示不正确的单元格

ios - 带有自定义 UICollectionViewLayout 的 UICollectionViewCell 仅在一个 subview 上创建视差动画

swift - 将 UICollectionView 集中在 tvOS 上的行

xcode - 如何在可以打开和关闭的循环中添加 SKnode