'Conditionally hide a section header of a grouped tableview with each section having title

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.



Solution 1:[1]

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

    return tableView.sectionHeaderHeight
}

Solution 2:[2]

So, I figured out the reason for header not being able to hide. If there is anything in the header title field, making the section height 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iulian Onofrei
Solution 2 Iulian Onofrei