首页 > 解决方案 > 具有多种数据类型的 CollectionView 组合布局

问题描述

我正在玩带有 Diffable DataSource 的 Compositional Layouts,到目前为止我很喜欢它。但我所有的努力都包括了单一类型的数据项。

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

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

enum DataItem: Hashable{
    case cars(Car)
    case airplane(Airplane)
}

dataSource初始化:

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)
}

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

理想情况下,我想做的是

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
}

我在这里想念什么?

标签: iosswiftcollectionviewdiffabledatasource

解决方案


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

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
}


推荐阅读