【问题标题】:CollectionView Compositional Layout with Multiple Data Types具有多种数据类型的 CollectionView 组合布局
【发布时间】:2020-07-18 07:29:02
【问题描述】:

我正在使用 Diffable DataSource 使用组合布局,到目前为止我很喜欢它。但我所有的努力都包含了一种类型的数据项。

我想要实现的是有两种不同类型的列表,比如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
}

我在这里错过了什么?

【问题讨论】:

    标签: ios swift collectionview diffabledatasource


    【解决方案1】:

    你走在正确的道路上。您缺少的部分是您需要使用您创建的聚合类型创建快照,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
    }
    
    

    【讨论】:

      猜你喜欢
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多