UITableView: hide header from empty section

You have to set tableView:heightForHeaderInSection: to 0 for the appropriate sections. This is something which changed fairly recently and got me in a couple places. From UITableViewDelegate it says…

Prior to iOS 5.0, table views would automatically resize the heights
of headers to 0 for sections where tableView:viewForHeaderInSection:
returned a nil view. In iOS 5.0 and later, you must return the actual
height for each section header in this method.

So you’ll have to do something like

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
        return 0;
    } else {
        // whatever height you'd want for a real section header
    }
}

Leave a Comment