Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewForHeaderInSection - What to return for no header?

I have a UIViewController with several UITableViews imbedded in it. For some of the tables, I need to show a custom header view with multiple labels. For other tables, I don't want to show a header at all (that is, I want the first cell in myTable2 to be right at the top of the frame for myTable2). Here's roughly what I have:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.myTable1)
    // Wants Custom Header
    {        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.contentSize.width,20);

        // ... Do stuff to customize view ...

        return view;
    }
    elseIf (tableView == self.myTable2)
    // Wants No header
    {
        return nil;
        // also tried
        // return [[UIView alloc] initWithFrame:CGRectMake(0,0,0,0)];
        // but that didn't work either
    }
}

This works great for the custom headers, but for the tables where I don't want any header, it's showing a white box. I figured that return nil; would prevent any header from being shown for that table. Is that assumption correct? Is there something else overwritting that? How can I make it so nothing shows?

like image 556
GeneralMike Avatar asked Feb 13 '14 20:02

GeneralMike


People also ask

How to add header and footer in tableView in swift?

To create a basic header or footer with a text label, override the tableView:titleForHeaderInSection: or tableView:titleForFooterInSection: method of your table's data source object. The table view creates a standard header or footer for you and inserts it into the table at the specified location.

What is header in swift?

For output message, the basic header identifies the application through which SWIFT has processed the message. The basic header also identifies the type of output data, the receiving logical terminal, and (if required) the output session number and output sequence number.


2 Answers

Whenever you implement the viewForHeaderInSection method you must also implement the heightForHeaderInSection method. Be sure to return 0 for the height for sections that have no header.

like image 59
rmaddy Avatar answered Oct 03 '22 19:10

rmaddy


If you use this way you don't need to calculate the height.

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 50

If you have empty sections you can set the height to zero or you don't need this method.

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 {
            return 0
        }
        return UITableView.automaticDimension
    }
like image 27
William Hu Avatar answered Oct 03 '22 19:10

William Hu