StructureKit 是控制非常非常复杂的表格或集合的最简单方式。
特点
🙉 忘记像尝试插入、删除、移动等...
这样的异常🙊 忘记numberOfRows, numberOfItems, cellForRow 等...
🙈 忘记insertRows, deleteRows 等...
😌 构建表格或集合视图最简单的方式🤩 自动计算动画的 diff(插入、删除、移动、更新)🙀 非常容易创建和控制不同单元格类型的集合🤨 计算 diff 时不会在内存中存储先前使用的模型🤗 使用单个cellModel
用于tableView
和collectionView
入门指南
安装
pod 'StructureKit'
模型
制作一些模型
// City will be used as cell
struct City {
let title: String
}
// Country will be used as section
struct Country {
let title: String
let cities: [City]
}
声明 City
模型以在 tableView
中使用。
我建议创建 cell viewModel,但为了简单演示,我们直接使用数据实体。
实现 StructurableIdentifable
以在 diffing 计算中识别模型(insert
、delete
、move
)
extension City: StructurableIdentifable {
func identifyHash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
实现 StructurableForTableView
以在 tableView
中使用,并使用模型数据配置单元格。
extension City: StructurableForTableView {
// Reuse identifier will be registered as class name
func configure(tableViewCell cell: CityTableViewCell) {
cell.textLabel?.text = name
}
}
ViewController
使用 tableView
实现 viewController
class TableViewController: UIViewController {
var countries: [Country] = []
@IBOutlet var tableView: UITableView!
let structureController = StructureController()
override func viewDidLoad() {
super.viewDidLoad()
loadCountries()
configureTableView()
makeStructure()
}
func loadCountries() {
// some data loading
self.countries = [
Country(title: "USA", cities: [City(title: "New York"), City(title: "Los Angeles"), City(title: "Cupertino")]),
Country(title: "Russia", cities: [City(title: "Moscow"), City(title: "Rostov-on-Don"), City(title: "Yeysk")])
]
}
// Register tableView and cell types in StructureController
func configureTableView() {
// You can make registration once per instance
structureController.register(tableView, cellModelTypes: [
City.self
])
}
// Create table structure
func makeStructure() {
let structure = countries.map { country in
var section = StructureSection(
identifier: country.title,
rows: country.cities
)
section.header = .text(country.name)
return section
}
structureController.set(structure: structure)
}
}
完成!