UITableViewDiffableDataSource: how to set section header titles?
Providing code example on @particleman's explanations.
struct User: Hashable {
var name: String
}
enum UserSection: String {
case platinum = "Platinum Tier"
case gold = "Gold Tier"
case silver = "Silver Tier"
}
class UserTableViewDiffibleDataSource: UITableViewDiffableDataSource<UserSection, User> {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let user = self.itemIdentifier(for: IndexPath(item: 0, section: section)) else { return nil }
return self.snapshot().sectionIdentifier(containingItem: user)?.rawValue
}
}
Update: Starting in beta 8, you can now implement tableView(_ tableView:, titleForHeaderInSection section:)
in a UITableViewDiffableDataSource subclass and it works properly.
The default behavior for populating the header title has always been a little strange to have in the data source. With UITableViewDiffableDataSource, Apple seems to be acknowledging such by not providing the default string-based behavior; however, the UITableViewDelegate methods continue to work as before. Implementing tableView(_:viewForHeaderInSection:)
by initializing and returning a UILabel with the desired section title and implementing tableView(_:heightForHeaderInSection:)
to manage the desired height works.