TableAdapter
一个用于构建复杂表格视图的数据驱动库。使用底层的自动 diffing 算法轻松更新具有动画效果的表格视图项。我们的目标是构建表格时考虑数据而不是索引路径。高级且灵活的 API 允许通过几行代码设置分节列表并更多地控制所需的表格。可重用的视图配置有助于以类型安全的方式保持代码整洁且稳定。
特性
- 基于自动差异化的动画表更新
- 线性时间差异算法
- 类型安全的单元格,通过协议实现设置头部/尾部
- 不再需要
dequeReusable...
- 不需要对单元格、表或模型进行子类化
- 从xib、Storyboard或代码初始化单元格
- 简单而灵活的分区构建
- 易于扩展
使用
1. 设置模型和可重用视图
1.1 模型设置
线单元项必须采用Hashable
协议。
1.2 单元格设置
表视图单元格应遵从 Configurable
协议以接收配置单元项。
extension Cell: Configurable {
public func setup(with item: User) {
textLabel?.text = item.name
}
}
1.3 首页/页脚视图设置
首页/页脚视图也应采用Configurable
协议来接收由Section
提供的配置项。
extension Header: Configurable {
public func setup(with item: String) {
textLabel?.text = item
}
}
2. 创建分区
分区类型 Section<Item, SectionId>
是一个泛型类型,开发者应提供单元格模型类型(Item
)和分区ID类型(SectionId
)。它包含项目信息、头部/底部配置(可选)并必须有唯一的 id
。
HeaderFooterConfig
包含所有关于分区头部/底部设置的配置信息。它有两种类型:默认和自定义头部/底部视图类型。
2.1 页眉/页脚默认标题
let section = Section<User, Int>(
id: 0,
items: [...],
header: .default(title: "Section Begin")
)
2.2 自定义页眉/页脚视图
let section = Section<User, Int>(
id: 0,
items: [...],
header: .custom(item: "Section Begin", reuseId: "FooterId")
)
节点:任何类型的项都可以用于设置页眉/页脚。
3. 创建适配器并填充它与分区
创建 TableAdapter<Item, SectionId>
。Item和分区ID是关联类型,类似于在《Section》中。
然后使用分区更新适配器。
class ViewController: UIViewController {
let tableView = ...
let users: [User] = [...]
private lazy var adapter = TableAdapter<User, Int>(
tableView: tableView,
cellIdentifierProvider: { (indexPath, item) -> String? in
return "Cell"
},
cellDidSelectHandler: { (table, indexPath, item) in
// Handle cell selection for item at indexPath
}
)
override func viewDidLoad() {
super.viewDidLoad()
setupTable()
let section = Section<User, Int>(
id: 0,
items: users,
header: .custom(item: "Begin", reuseId: "HeaderId"),
footer: .custom(item: "End", reuseId: "FooterId"),
)
adapter.update(with: [section], animated: true)
}
func setupTable() {
tableView.register(Cell.self, forCellReuseIdentifier: "Cell")
tableView.register(Header.self, forHeaderFooterViewReuseIdentifier identifier: "HeaderId")
tableView.register(Footer.self, forHeaderFooterViewReuseIdentifier identifier: "FooterId")
}
}
注意:此适配器类型将表格视图代理设置为自身。要处理其他表格视图代理方法,必须从 TableAdapter
继承并实现它们。
您也可以使用 currentSections: [Section]
变量获取当前适配器分区。
发送者
有时您需要为单元格、表头或表脚设置委托代理。为此,表适配器具有 sender
属性,该属性将被传递到采用 SenderConfigurable
协议的可配置视图。
extension Cell: SenderConfigurable {
func setup(with item: Item, sender: ViewController) {
textLabel?.text = object.name
delegate = sender
}
}
单单元格类型
要使用单单元格类型,创建不包含 CellReuserIdentifierProvider
的适配器。
lazy var adapter = TableAdapter<User, Int>(tableView: tableView)
并使用故事板或代码注册单元格,每次都指定默认的单元格重用标识符,内部默认为 "Cell"。
tableView.register(Cell.self, forCellReuseIdentifier: adapter.defaultCellIdentifier)
要求
- Swift 4.2+
- iOS 9.0+
安装
CocoaPods
以下内容添加到 Podfile
pod 'TableAdapter'
Carthage
在Cartfile
中加入以下内容
github "MobileUpLLC/TableAdapter"
手册
下载并将文件从源文件夹拖动到您的Xcode项目中。
许可协议
TableAdapter遵守 MIT 许可协议。