Home > OS >  Conditionally remove a section header of a grouped tableview
Conditionally remove a section header of a grouped tableview

Time:12-08

I have a condition based on which, I need to hide the header for my static tableView. My tableview's style is grouped and every section has a title in the section Header.

I am setting the height of the 5th section to CGFloat.leastNormalMagnitude because I want it to disappear but it is not working.

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if hideFifthRow{
             if section == 4 {
                return CGFloat.leastNormalMagnitude
            }
        }
        return tableView.sectionHeaderHeight
}

Can anyone please help.

CodePudding user response:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if hideFifthRow{
if section == 4 {
return 0.1
}
}
return tableView.sectionHeaderHeight
}

CodePudding user response:

So, I figured out the reason for header not being able to hide. If there is anything in the header title field, making the the being to be the smallest possible height will not work.

So, on top of

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if hideFifthRow{
             if section == 4 {
                return CGFloat.leastNormalMagnitude
            }
        }
        return tableView.sectionHeaderHeight
}

Here is what I need to perform additionally-

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if hideFifthRow{
         if section == 4 {
            return nil
        }
    }
    return sectionTitles[section]
}

Note, I had to store the header titles in an array and set the titles programmatically from titleForHeaderInSection delegate method too. For my hiding clause, I had to return nil to get rid of the title first.

  • Related