问题描述
如何使用Diffable DataSource在Tableview中创建多个节??
我使用Diffable DataSource创建了简单的TableView,但是我不能理解如何使用标题设置多个节。?
解决方法
首先,您需要通过调用其appendSections(_:)
方法将部分添加到快照中。
然后使用appendItems(_:toSection:)
将项目添加到您的部分中。
最后,在子类UITableViewDiffableDataSource
的类中,您需要重写方法tableView(_:titleForHeaderInSection:)
。在此方法的实现中,您可以调用snapshot().sectionIdentifiers[section]
来获取节标识符,然后让您返回该节的适当标题。
official documentation有一个使用单个节的示例,因此通过为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","")
}
}
}