首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有多种单元格类型的DiffableDataSource

具有多种单元格类型的DiffableDataSource
EN

Stack Overflow用户
提问于 2019-08-14 23:09:20
回答 2查看 2.2K关注 0票数 12

我正在研究iOS13中可用的DiffableDataSource (或者在这里向后移植:https://github.com/ra1028/DiffableDataSources),但是不知道如何在集合或表视图中支持多种单元格类型。

苹果公司的示例代码1有:

代码语言:javascript
复制
var dataSource: UICollectionViewDiffableDataSource<Section, OutlineItem>! = nil

这似乎强制数据源为单一单元格类型。如果我为另一种单元格类型创建一个单独的数据源-那么不能保证两个数据源不会同时调用apply -这将导致可怕的NSInternalInconsistencyException -任何试图使用performBatchUpdates手动设置单元格插入/删除动画的人都熟悉这种情况。

我是不是漏掉了什么明显的东西?

EN

回答 2

Stack Overflow用户

发布于 2020-01-16 05:08:37

我将不同的数据包装在一个带有关联值的enum中。在我的例子中,我的数据源是UICollectionViewDiffableDataSource<Section, Item>类型,其中Item

代码语言:javascript
复制
enum Item: Hashable {
  case firstSection(DataModel1)
  case secondSection(DataModel2)
}

然后,在传递给数据源初始化的闭包中,您将获得一个Item,并且可以根据需要测试和解包数据。

(我要补充的是,您应该确保与支持相关的值是Hashable,否则您将需要实现它。这就是diff‘’ing算法用来识别每个单元格,并解决移动等问题的方法)

票数 17
EN

Stack Overflow用户

发布于 2019-08-15 04:28:11

你肯定需要有一个单一的数据源。

关键是使用更通用的类型。Swift的AnyHashable在这里运行得很好。您只需要将AnyHashable的实例转换为一个更具体的类。

代码语言:javascript
复制
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枚举如下所示:

代码语言:javascript
复制
    enum Section: Int, CaseIterable {
        case articles
        case articleImages

        var cellIdentifier: String {
            switch self {
            case .articles:
                return "articleCell"
            case .articleImages:
                return "imagesCell"
            }
        }
    }
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57497461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档