How to Create Multiple Section In Tableview Using Diffable DataSource.?
I create Simple TableView using Diffable DataSource But I can't underStand How to Set Multiple Section With Tittle.?
How to Create Multiple Section In Tableview Using Diffable DataSource.?
I create Simple TableView using Diffable DataSource But I can't underStand How to Set Multiple Section With Tittle.?
The official documentation has an example that uses a single section, so by providing the second argument to appendItems
you can target which section should be populated with the given items, i.e:
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)
If you'd like to provide the section titles, I'd subclass the UITableViewDiffableDataSource
and override the relevant methods, i.e:
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", "")
}
}
}
First, you need to add your sections to your snapshot by calling its
appendSections(_:)
method.Then you add items to your sections with
appendItems(_:toSection:)
.Finally, in your class that subclasses
UITableViewDiffableDataSource
, you need to override the methodtableView(_:titleForHeaderInSection:)
. In the implementation of this method you can callsnapshot().sectionIdentifiers[section]
to get the section identifier which then lets you return an appropriate title of the section.