所以我最近才用Diffable DataSource做了一些构图布局,到目前为止我很喜欢它。但我所有的努力都只包含一种类型的数据项。
我想要实现的是有两种不同类型的列表,比如Car和Airplane
到目前为止,我所做的就是创建布局,创建一个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
}对于如何实现这一点有什么建议吗?提前感谢!这里我漏掉了什么?
发布于 2020-07-23 05:12:44
你走在正确的道路上。您缺少的部分是,您需要使用您创建的聚合类型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
}https://stackoverflow.com/questions/61057438
复制相似问题