用 ❤️ 由 Ryo Aoyama 制作
Apple 在 WWDC 2019 上发布了可 диффинг 数据源。
这是一个很棒的 API,可以轻松地使用自动 диффинг 更新我们的表格视图和集合视图项。
但是,在生产服务中使用它还需要一段时间。
那是因为它需要最新的操作系统才能使用。
DiffableDataSources 使从现在开始引入几乎相同的功能成为可能。
使用精密的开源 DifferenceKit 作为算法引擎。
它速度极快,并完全避免了同步错误、异常和崩溃。
performBatchUpdates
进行 диффинг 更新。DiffableDataSources
具有不同的类名,以避免与官方 API 冲突。
对应表如下。
官方 | 向后移植 |
---|---|
NSDiffableDataSourceSnapshot | DiffableDataSourceSnapshot |
UITableViewDiffableDataSource | TableViewDiffableDataSource |
UICollectionViewDiffableDataSource | CollectionViewDiffableDataSource |
NSCollectionViewDiffableDataSource | CocoaCollectionViewDiffableDataSource |
$ git clone https://github.com/ra1028/DiffableDataSources.git
$ cd DiffableDataSources/
$ make setup
$ open DiffableDataSources.xcworkspace
首先,定义表示 section 的类型。
它应该遵循 Hashable
协议,以便从所有 section 中识别。
可以使用枚举类型,因为它默认遵循 Hashable
协议,非常方便。
enum Section {
case main
}
然后,定义遵循 Hashable
协议的 item 类型。
struct User: Hashable {
var name: String
}
创建一个数据源对象,它将自动设置为表格视图。
您应该通过闭包出列非空单元格。
final class UsersViewController: UIViewController {
let tableView: UITableView = ...
lazy var dataSource = TableViewDiffableDataSource<Section, User>(tableView: tableView) { tableView, indexPath, user in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = user.name
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
}
通过调解 DiffableDataSourceSnapshot
直观地管理和更新数据源。
在您应用编辑后的 snapshot 对象之前,UI 不会更新。
通过应用编辑后的 snapshot,使用自动计算的 диффинг 动画更新 UI。
let users = [
User(name: "Steve Jobs"),
User(name: "Stephen Wozniak"),
User(name: "Tim Cook"),
User(name: "Jonathan Ive")
]
let snapshot = DiffableDataSourceSnapshot<Section, User>()
snapshot.appendSections([.main])
snapshot.appendItems(users)
dataSource.apply(snapshot) {
// completion
}
查看文档以获取更详细的 API 信息。
将以下内容添加到您的 Podfile
pod 'DiffableDataSources'
将以下内容添加到您的 Cartfile
github "ra1028/DiffableDataSources"
将以下内容添加到您的 Package.swift
的 dependencies 中
.package(url: "https://github.com/ra1028/DiffableDataSources.git", from: "x.x.x")
欢迎提交 pull request、bug 报告和功能请求 🚀
请参阅 CONTRIBUTING 文件,了解如何为 DiffableDataSources 做出贡献。
一个快速且灵活的 O(n) 差异算法框架,用于 Swift 集合。
一个声明式库,用于在 UITableView 和 UICollectionView 中构建基于组件的用户界面。
DiffableDataSources 在 Apache 2.0 许可证 下发布。