Swift - how to make custom header sections for UITableView using enum?

1.5k Views Asked by At

Hi guys inside my tableView class i have following enum

enum tabelSecion { 
    case action 
    case drama 
    case comedy
}

i need to use this enum to have 3 different section header. also i created a nib to represents a custom sectionHeaderCell which has only a label inside it.how can i show section headers? appreciate for your help

1

There are 1 best solutions below

3
On

You can do it by extending your enum with a dynamic var SectionTitle.

enum TabelSection: Int, CaseIterable { 
    case action 
    case drama 
    case comedy

    var sectionTitle: String {
        switch self {
        case action: return "Action"
        ...
        }
    }
}

By making you enum an Int, it is possible to init it with a rawValue. The rawValue to init it is the section it you get from the TableView Method.

The CaseIterable is also quit nice so you can get the number cases (=sections) from it for the numberOfSections Method.

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return TabelSection(rawValue: section)?.sectionTitle
}

Edit: To display a headerView for each section of the tableView change the TableViewstyle to Grouped

In your code just provide the tableView with the correct amount of sections.

override func numberOfSections(in tableView: UITableView) -> Int {
    return TabelSection.allCases.count
}

If you really need a custom HeaderView you may use the following Method to do so

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    ...
}