如何使用Diffable DataSource在表视图中创建多个节。?
我使用Diffable DataSource创建了Simple TableView,但我无法理解如何用标题设置多个节。?
首先,您需要通过调用其appendSections(_:)
方法将节添加到快照中。
然后使用appendItems(_:toSection:)
将项目添加到分区中。
最后,在UITableViewDiffableDataSource
的子类中,需要重写方法tableView(_:titleForHeaderInSection:)
。在这个方法的实现中,您可以调用snapshot().sectionIdentifiers[section]
来获取节标识符,然后让您返回节的适当标题。
官方文档中有一个使用单个节的示例,因此通过向appendItems
提供第二个参数,您可以确定应该用给定项填充哪个节,即:
enum MySectionType {
case fruits
case beverage
}
// Create a snapshot
var snapshot = NSDiffableDataSourceSnapshot<MySectionType, String>()
// Populate the snapshot
snapshot.appendSections([.fruits, .beverage])
snapshot.appendItems(["🍌", "🍎"], toSection: .fruits)
snapshot.appendItems(["coke", "pepsi"], toSection: .beverage)
// Apply the snapshot
dataSource.apply(snapshot, animatingDifferences: true)
如果你想提供章节标题,我会将UITableViewDiffableDataSource
子类化并覆盖相关方法,即:
class MyDataSource: UITableViewDiffableDataSource<MySectionType> {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionIdentifier = self.snapshot().sectionIdentifiers[section]
switch sectionIdentifier {
case .fruits:
return NSLocalizedString("Fruits", "")
case .beverage:
return NSLocalizedString("Beverage", "")
}
}
}