【发布时间】:2025-11-26 06:15:01
【问题描述】:
我目前正在学习 DiffableDataSource。我正在使用 NSDiffableDataSourceSectionSnapshot(),而不是 NSDiffableDataSourceSnapshot() 为我的数据源创建部分
根据单击的部分,我想增加部分模型数据counter 属性。但是,我在使用 sectionSnapshot() 重新加载该部分时遇到问题。后面的counter 属性总数将显示为sectionHeader。
下面是我的结构
struct TestParent: Hashable {
var title = String()
var counter = 0
var children = [TestChildren]()
}
struct TestChildren: Hashable {
var title = String()
var name = String()
}
下面是我的实现代码
@IBOutlet weak var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<AnyHashable, AnyHashable>?
private var parents = [TestParent]()
override func viewDidLoad() {
super.viewDidLoad()
self.createSampleArray()
self.configureAllCollectionViews()
}
fileprivate func createSampleArray() {
self.parents = [
TestParent(title: "Parent 1",
children: [
TestChildren(title: "Child 1 - A"),
TestChildren(title: "Child 1 - B"),
TestChildren(title: "Child 1 - C"),
]),
TestParent(title: "Parent 2",
children: [
TestChildren(title: "Child 2 - A"),
TestChildren(title: "Child 2 - B"),
TestChildren(title: "Child 2 - C"),
TestChildren(title: "Child 2 - D"),
]),
]
}
private func parentSnapshot(_ parent: TestParent) -> NSDiffableDataSourceSectionSnapshot<AnyHashable> {
var snapshot = NSDiffableDataSourceSectionSnapshot<AnyHashable>()
snapshot.append(parent.children)
return snapshot
}
private func applyInitialSnapshot() {
for eachParent in parents {
self.dataSource?.apply(self.parentSnapshot(eachParent), to: eachParent)
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.check(indexPath: indexPath)
}
fileprivate func check(indexPath: IndexPath) {
guard let children = self.dataSource?.itemIdentifier(for: indexPath) as? TestChildren else { return }
guard var section = self.dataSource?.snapshot().sectionIdentifier(containingItem: children) as? TestParent else { return }
section.counter += 1
var snapshot = self.dataSource?.snapshot()
snapshot?.reloadSections([section])
self.dataSource?.apply(snapshot!)
}
如何在每次单击单元格时更新部分数据模型counter 属性?构建collectionView UI没有问题
我在这里缺少什么?谢谢...
【问题讨论】: