我在我的UITableView中使用了一个UITableViewDiffableDataSource,它可以正常工作。然而,我在更新快照中的项目时遇到了问题。我有一个简单的样本;
enum Section {
case one
}
struct Item: Hashable {
let identifier: Int
let text: String
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
public static func == (lhs: Item, rhs: Item) -> Bool {
return lhs.identifier == rhs.identifier
}
}使用以下命令创建初始快照
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.one])
snapshot.appendItems([
Item(identifier: 1, text: "One"),
Item(identifier: 2, text: "Two"),
Item(identifier: 3, text: "Three")
])
dataSource.apply(snapshot)如果我尝试使用以下命令更新项目
var snapshot = dataSource.snapshot()
snapshot.reloadItems([
Item(identifier: 2, text: "Foo")
])
dataSource.apply(snapshot)什么都没发生。我的预期结果是将identifier =2的项目的text更新为"Foo“。注我在这里没有包含表视图单元格提供程序代码。
我读过类似的帖子,比如How to update a table cell using diffable UITableView和Can UITableViewDiffableDataSource detect an item changed?,但答案并不明显。
发布于 2020-09-25 01:50:08
如果您想要一个自定义的text,您只需要在Equatable协议函数中添加==属性:
public static func == (lhs: Item, rhs: Item) -> Bool {
return lhs.identifier == rhs.identifier && lhs.text == rhs.text
}在此之后,数据源可以找出差异并正确更新项。
或者,您可以将其全部删除,并保留结构中的默认实现。
还有另一种更新数据的方法。将更新后的数组追加到新快照,并将其应用于数据源。
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.one])
snapshot.appendItems([
Item(identifier: 1, text: "One"),
Item(identifier: 2, text: "Foo"), // Updated item
Item(identifier: 3, text: "Three")
])
dataSource.apply(snapshot)数据源会自行发现差异并重新加载表视图中的项。
如果你感兴趣,这里有更多的细节here
https://stackoverflow.com/questions/62870296
复制相似问题