-1

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

Deitsch
  • 1,610
  • 14
  • 28
  • I guess [this](https://stackoverflow.com/a/31741336/5928311) can help you and read comments also. I mean [this](https://gist.github.com/whiskey/4def64050c7afdadb6c3) – Vadim Nikolaev Sep 23 '20 at 07:38

1 Answers1

1

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? {
    ...
}
Deitsch
  • 1,610
  • 14
  • 28
  • thanks for your help but how should i dequeue customHeaderSectionCell which has only a label inside? – David Harinson Sep 23 '20 at 08:10
  • because the section header cell's label needs to get updated to "Action", "Drama"... – David Harinson Sep 23 '20 at 08:20
  • You do not need a custom cell for this. The headerView already provides a label. Overriding `titleForHeaderInSection` allows you to configure which text will be displayed for each section – Deitsch Sep 23 '20 at 08:22