3

I try to add header title for each section in UITableView, but in this case it's UITableViewDiffableDataSource and I don't have any idea where I should do that. A part of my code:

private func prepareTableView() {
    tableView.delegate = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    dataSource = UITableViewDiffableDataSource<Sections, User>(tableView: tableView, cellProvider: { (tableView, indexPath, user) -> UITableViewCell? in
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = user.name
        return cell
    })
}

private func addElement(_ user: User) {
    var snap = NSDiffableDataSourceSnapshot<Sections, User>()
    snap.appendSections([.main, .second])
    if isFirst {
        users.append(user)
    } else {
        secondUsers.append(user)
    }
    snap.appendItems(users, toSection: .main)
    snap.appendItems(secondUsers, toSection: .second)
    isFirst.toggle()
    dataSource.apply(snap, animatingDifferences: true, completion: nil)
    dataSource.defaultRowAnimation = .fade
}

UICollectionViewDiffableDataSource has a parameter supplementaryViewProvider where user can configure headers. Does exist something like this in UITableViewDiffableDataSource

PiterPan
  • 1,760
  • 2
  • 22
  • 43

2 Answers2

14

I was able to do that by subclassing the UITableViewDiffableDataSource class like this:

class MyDataSource: UITableViewDiffableDataSource<Sections, User> {

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Hello, World!"
    }
}

and then in your code instead of this:

dataSource = UITableViewDiffableDataSource<Sections, User>

use your own Data Source class:

dataSource = MyDataSource<Sections, User>
Tung Fam
  • 7,899
  • 4
  • 56
  • 63
-3

Yes, see the supplementaryViewProvider property of UICollectionViewDiffableDataSource

Apple doesn't really have much documentation of it, but you can initialize it with a closure similar to how you initialize the diffable data source itself. It returns a UICollectionReusableView which can either be a generic view, or one of your header or footer view subclasses.

oflannabhra
  • 661
  • 5
  • 18