【发布时间】:2021-06-07 22:22:06
【问题描述】:
参考this的问题,我想做类似的事情。我尝试通过两种方式为我的集合视图复制我的 diffable 数据源的答案。
第一种方法是为同一个集合视图创建另一个可区分的数据源。当 indexpath.row 小于我的数组的计数时,将配置实际的项目单元格,而当它等于计数时,它将显示我的静态单元格。
//configure cells: categoryCollectionViewDataSource is the actual datasource for the items that I want to display.
categoryCollectionViewDataSource = UICollectionViewDiffableDataSource<Int, MistakeCategory>(collectionView: categoryCollectionView){
(collectionView, indexPath, mistakeCategory) in
if indexPath.row < (subjectSelected?.MistakeCategories.count)! {
let cell = self.categoryCollectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCollectionViewCell", for: indexPath) as! CategoryCollectionViewCell
cell.setProperty(SubjectCategory: nil, MistakeCategory: self.subjectSelected?.MistakeCategories[indexPath.row])
return cell
} else {
return nil
}
}
//configure cells: staticCollectionViewDataSource is the data source for the cell that I want to display no matter what. it is displayed at the last row of the indexpath.
staticCellCollectionViewDataSource = UICollectionViewDiffableDataSource<Int, Int>(collectionView: categoryCollectionView){
(collectionView, indexPath, mistakeCategory) in
if indexPath.row == subjectSelected?.MistakeCategories.count {
let cell = self.categoryCollectionView.dequeueReusableCell(withReuseIdentifier: "StaticCreateNewCategoryCollectionViewCell", for: indexPath) as! StaticCreateNewCategoryCollectionViewCell
return cell
} else {
return nil
}
}
这里是我在配置单元格后更新在 viewDidLoad 上运行的 diffable 数据源的地方:
internal func updateCategoryCollectionView() {
var snapshot = NSDiffableDataSourceSnapshot<Int, MistakeCategory>()
snapshot.appendSections([0])
snapshot.appendItems(Array(subjectSelected!.MistakeCategories))
categoryCollectionViewDataSource.apply(snapshot) //error: 'attempt to insert section 0 but there are only 0 sections after the update'
var staticSnapshot = NSDiffableDataSourceSnapshot<Int,Int>()
staticSnapshot.appendSections([0])
staticSnapshot.appendItems([0])
staticCellCollectionViewDataSource.apply(staticSnapshot)
}
这会导致错误“尝试插入第 0 节,但更新后只有 0 节”。我曾尝试实现 UICollectionViewDataSource 的功能,但遇到了如何合并这两种类型的数据源的问题。
因此,我不知道如何在行尾创建一个静态自定义单元格。
【问题讨论】: