这是一个库,通过管理数据并确保调用正确的插入/删除操作,使处理 CollectionView 和 UITableViews 更加容易。
它类似于 UIKit DiffableDataSource,但增加了一个功能:它支持在不替换实际单元格的情况下,以动画方式更新现有单元格。 这确保了飞行中的动画不会中断。
一切的基础是快照。 快照是数据在给定时刻的视图。 如果我们有两个快照,我们可以计算这两个快照的 diff
(差异),并准确地知道要更新的内容。
快照管理 Item (项) 的 Section (节)。 具体的 Item 类型和 Section 类型需要实现 Identifiable
协议,以便它们具有稳定的 ID,该 ID 不依赖于其数据。
作为一种优化,还存在 SingleSectionSnapshot
,它仅管理 Item
的列表:如果您只有一个节,这将很有用。
有三种变体
TableViewDataSource
管理表视图所有节中的数据SingleSectionTableViewDataSource
管理只有单个节的表视图中的数据TableViewSectionDataSource
保留一个节中的数据,而您负责其他节并实现实际数据。let dataSource = TableViewDataSource(tableView, cellProvider: { tableView, item, indexPath
return tableView.dequeueCellWithIdentifier("Cell")
})
dataSource.cellUpdater = { tableView, cell, item, indexPath, animated in
cell.textLabel?.setText(item.text, animated: animated)
}
var snapshot = dataSource.currentSnapshot
snapshot.addItems([Item(text: "Item 1")], to: .first)
snapshot.addItems([Item(text: "Item 2")], to: .first)
snapshot.addItems([Item(text: "Item 3")], to: .third)
dataSource.apply(snapshot, animated: true)
有两种变体
CollectionViewDataSource
管理集合视图所有节中的数据SingleSectionCollectionViewDataSource
管理只有单个节的集合视图中的数据