UICollectionViewDiffableDataSource 在应用时不能正确设置动画

问题描述

我有一个项目列表,它们在列表中按数量降序显示。我按名称对它们进行哈希处理,因此当我更改金额时,它们应该在应用时顺利重新排序。 当我在 apply(snapshot,animatingDifferences: true)调用 UICollectionViewDiffableDataSource 函数时,它不会以流畅的动画重新排列单元格,而是闪烁,并且一切都在没有“重新排序”的情况下就位。

struct Item: Hashable {
    let name: String
    let amount: Int

    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
    }
}

// when user taps,I call this
dataSource.apply(makeSnapshot())

解决方法

结果 UICollectionViewDiffableDataSource 不仅使用散列来判断哪个项目是哪个,还使用 ​​== 运算符。 这解决了问题:

struct Item: Hashable {
    let name: String
    let amount: Int

    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
    }

    static func == (lhs: Category,rhs: Category) -> Bool {
        return lhs.name == rhs.name
    }
}