I am trying to set up an UITableView with sections using the new UITableViewDiffableDataSource within an UITableViewController.
Everything seems to work fine except setting the section header titles.
According to Apple's documentation, UITableViewDiffableDataSource conforms to UITableViewDataSource, so I was expecting this to be possible.
I have tried:
but both ways lead to no result (Xcode 11 and iOS13 beta 3).
Is there currently a way to set the section header titles using UITableViewDiffableDataSource?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With