ios - 具有多种数据类型的 CollectionView 组合布局
问题描述
我正在玩带有 Diffable DataSource 的 Compositional Layouts,到目前为止我很喜欢它。但我所有的努力都包括了单一类型的数据项。
我想要实现的是有两种不同类型的列表,比如说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
}
我在这里想念什么?
解决方案
你在正确的道路上。您缺少的部分是您需要使用您创建的聚合类型创建快照,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
}
推荐阅读
- c# - 使用 iText 7 创建的可见签名未在 chrome 中显示
- autohotkey - 如何调整作为参数传递的数组的索引?
- bots - 如何在电报机器人中每 1 行显示 1 个按钮?
- opencv - KAZE 和 AKAZE 中的八度音阶和子级别是什么?
- javascript - 来自restapi的图像/ png响应未显示在浏览器中
- python-3.x - asset_url_for() 在烧瓶饼干切割器(flask-webpack)中返回 None
- laravel - 当laravel中的条带支付错误时如何在try/catch中重定向
- python - 为什么我得到 AttributeError: 'numpy.ndarray' 对象在 python 中没有属性 'replace'?
- python - 将两个数据帧存储在 alist 中,对它们执行操作,但原始 df 保持不变
- c# - 在程序生成中对齐生成点