Dhruv Nakrani
Dhruv Nakrani

Reputation: 23

UITableView diffable data source

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

Upvotes: 1

Views: 2031

Answers (2)

pronebird
pronebird

Reputation: 12260

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

}

Upvotes: 1

Vadim Belyaev
Vadim Belyaev

Reputation: 2859

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.

Upvotes: 1

Related Questions