【问题标题】:Swift NSDiffableDataSourceSectionSnapshot Reload SectionSwift NSDiffableDataSourceSectionSnapshot 重新加载部分
【发布时间】: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没有问题

我在这里缺少什么?谢谢...

【问题讨论】:

    标签: ios swift uikit


    【解决方案1】:

    您的部分是一个结构体(一种值类型),因此当您更改部分计数时,您会更改可区分数据源用作标识符的哈希值。它不知道您正在更新预先存在的部分;它认为这是一个全新的部分。

    一般来说,节标识符应该是标识符并且不包含可变状态。您可以编写散列和相等方法来忽略该可变状态,但考虑它会很痛苦,因此只需将实际数据保存在其他地方并根据部分标识符进行查找。

    【讨论】:

    • 啊……这就是为什么……谢谢先生的解释。真的很感激!