首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有多种数据类型的CollectionView组合布局

具有多种数据类型的CollectionView组合布局
EN

Stack Overflow用户
提问于 2020-04-06 18:13:33
回答 1查看 767关注 0票数 6

所以我最近才用Diffable DataSource做了一些构图布局,到目前为止我很喜欢它。但我所有的努力都只包含一种类型的数据项。

我想要实现的是有两种不同类型的列表,比如CarAirplane

到目前为止,我所做的就是创建布局,创建一个Enum

代码语言:javascript
复制
enum DataItem: Hashable{
        case cars(Car)
        case airplane(Airplane)
 }

和dataSource初始化:

代码语言:javascript
复制
func configureDataSource(){
        dataSource = UICollectionViewDiffableDataSource
        <Section, DataItem>(collectionView: collectionView) {
            (collectionView: UICollectionView, indexPath: IndexPath, dataItem: DataItem) -> UICollectionViewCell in

            switch dataItem {
            case .cars(let car):
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CarCell.reuseIdentifier, for: indexPath) as? CarCell else {fatalError("Couldn't Create New Cell")}
                ....
                return cell
            case .airplanes(let airplane):
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AirplaneCell.reuseIdentifier, for: indexPath) as? AirplaneCell else {
                    fatalError("Couldn't Create New Cell")
                }
                ....
                return cell
            }
        }
        dataSource.apply(snapshotForCurrentState(), animatingDifferences: false)
    }

现在我被卡住的部分是创建快照。

理想情况下,我想要做的是

代码语言:javascript
复制
func snapshotForCurrentState() -> NSDiffableDataSourceSnapshot<Section, DataItem>{
    var snapshot = NSDiffableDataSourceSnapshot<Section, DataItem>()
    snapshot.appendSections(Section.allCases)
    snapshot.appendItems([cars], toSection: Section.cars)
    snapshot.appendItems([airplanes], toSection: Section.airplanes)
    return snapshot
}

对于如何实现这一点有什么建议吗?提前感谢!这里我漏掉了什么?

EN

回答 1

Stack Overflow用户

发布于 2020-07-23 05:12:44

你走在正确的道路上。您缺少的部分是,您需要使用您创建的聚合类型DataItem来创建快照。

代码语言:javascript
复制
func snapshotForCurrentState() -> NSDiffableDataSourceSnapshot<Section, DataItem>{
    var snapshot = NSDiffableDataSourceSnapshot<Section, DataItem>()
    snapshot.appendSections(Section.allCases)

    let carItems = cars.map { DataItem.car($0) }
    snapshot.appendItems(carItems, toSection: Section.cars)

    let airplaneItems = airplanes.map { DataItem.airplane($0) }
    snapshot.appendItems(airplaneItems, toSection: Section.airplanes)
    return snapshot
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61057438

复制
相关文章

相似问题

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