Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewDiffableDataSource: how to set section header titles?

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:

  1. overriding tableView(_ tableView:, titleForHeaderInSection section:) in the UITableViewController class
  2. subclassing UITableViewDiffableDataSource and implementing tableView(_ tableView:, titleForHeaderInSection section:) in the subclass

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?

like image 505
mmklug Avatar asked Jul 17 '19 13:07

mmklug


2 Answers

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
    }
}
like image 121
Brandon WongKS Avatar answered Nov 07 '22 08:11

Brandon WongKS


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.

like image 20
particleman Avatar answered Nov 07 '22 08:11

particleman