UITableView diffable data source

1.8k Views Asked by At

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.?

2

There are 2 best solutions below

0
On

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 method tableView(_:titleForHeaderInSection:). In the implementation of this method you can call snapshot().sectionIdentifiers[section] to get the section identifier which then lets you return an appropriate title of the section.

0
On

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", "")
    }
  }

}