Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Header Name in UITableViewDiffableDataSource

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

like image 444
PiterPan Avatar asked Feb 04 '26 08:02

PiterPan


1 Answers

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>
like image 187
Tung Fam Avatar answered Feb 06 '26 06:02

Tung Fam