How to set the height of table header in UITableView?

I have gone through Apple docs about UITableView class and delegate reference but couldn't find the way to set the table header height explicitly.

I set Table cell height using following delegate:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

and set section header/footer height using following delegates.

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

Could anyone please help me to set the table header/footer height?

Thanks.


Solution 1:

Just set the frame property of the tableHeaderView.

Solution 2:

I found a nice hack. Add the below line after modifying the frame propery

self.tableView.tableHeaderView = self.tableView.tableHeaderView;

The trick is (I think) that the UITableView is caching the height (the frame actually) when you assign the view to the tableHeaderView property. The above line just assigns the height again.

Solution 3:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    sizeHeaderToFit()
}

private func sizeHeaderToFit() {
    let headerView = tableView.tableHeaderView!

    headerView.setNeedsLayout()
    headerView.layoutIfNeeded()

    let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
    var frame = headerView.frame
    frame.size.height = height
    headerView.frame = frame

    tableView.tableHeaderView = headerView
}

More details can be found here

Solution 4:

In case you still need it, have you tried to set the property

self.tableView.tableHeaderView 

If you calculate the heigh you need, and set a new view for tableHeaderView:

CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];

It should work.

Solution 5:

It works with me only if I set the footer/header of the tableview to nil first:

self.footer = self.searchTableView.tableFooterView;
CGRect frame = self.footer.frame;
frame.size.height = 200;
self.footer.frame = frame;
self.searchTableView.tableFooterView = nil;
self.searchTableView.tableFooterView = self.footer;

Make sure that self.footer is a strong reference to prevent the footer view from being deallocated