UITableView: hide header from empty section UITableView: hide header from empty section ios ios

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    }}


What if in – tableView:viewForHeaderInSection: you return nil if the section count is 0.

EDIT :You can use numberOfRowsInSection for obtaining the number of elements in the section.

EDIT: Probably you should return nil also in titleForHeaderInSection if numberOfRowsInSection is 0.

EDIT: Did you implement the following method?

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

EDIT : Swift 3 example

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {    switch section {    case 0:        if self.tableView(tableView, numberOfRowsInSection: section) > 0 {            return "Title example for section 1"        }    case 1:        if self.tableView(tableView, numberOfRowsInSection: section) > 0 {            return "Title example for section 2"        }    default:        return nil // when return nil no header will be shown    }    return nil}


In my strange situation I have to return:

viewForHeaderInSection -> nil

 viewForFooterInSection -> nil (don't forget about footer!)

heightForHeaderInSection -> 0.01 (not zero!)

 heightForFooterInSection -> 0.01

only in this case empty sections disappear completely