我正在研究iOS13中可用的DiffableDataSource (或者在这里向后移植:https://github.com/ra1028/DiffableDataSources),但是不知道如何在集合或表视图中支持多种单元格类型。
苹果公司的示例代码1有:
var dataSource: UICollectionViewDiffableDataSource<Section, OutlineItem>! = nil这似乎强制数据源为单一单元格类型。如果我为另一种单元格类型创建一个单独的数据源-那么不能保证两个数据源不会同时调用apply -这将导致可怕的NSInternalInconsistencyException -任何试图使用performBatchUpdates手动设置单元格插入/删除动画的人都熟悉这种情况。
我是不是漏掉了什么明显的东西?
发布于 2020-01-16 05:08:37
我将不同的数据包装在一个带有关联值的enum中。在我的例子中,我的数据源是UICollectionViewDiffableDataSource<Section, Item>类型,其中Item是
enum Item: Hashable {
case firstSection(DataModel1)
case secondSection(DataModel2)
}然后,在传递给数据源初始化的闭包中,您将获得一个Item,并且可以根据需要测试和解包数据。
(我要补充的是,您应该确保与支持相关的值是Hashable,否则您将需要实现它。这就是diff‘’ing算法用来识别每个单元格,并解决移动等问题的方法)
发布于 2019-08-15 04:28:11
你肯定需要有一个单一的数据源。
关键是使用更通用的类型。Swift的AnyHashable在这里运行得很好。您只需要将AnyHashable的实例转换为一个更具体的类。
lazy var dataSource = CollectionViewDiffableDataSource<Section, AnyHashable> (collectionView: collectionView) { collectionView, indexPath, item in
if let article = item as? Article, let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Section.articles.cellIdentifier, for: indexPath) as? ArticleCell {
cell.article = article
return cell
}
if let image = item as? ArticleImage, let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Section.trends.cellIdentifier, for: indexPath) as? ImageCell {
cell.image = image
return cell
}
fatalError()
}Section枚举如下所示:
enum Section: Int, CaseIterable {
case articles
case articleImages
var cellIdentifier: String {
switch self {
case .articles:
return "articleCell"
case .articleImages:
return "imagesCell"
}
}
}https://stackoverflow.com/questions/57497461
复制相似问题