table header view height is wrong when using auto layout, IB, and font sizes

Note: A Swift 3+ version can be found here: https://gist.github.com/marcoarment/1105553afba6b4900c10#gistcomment-1933639


The idea is to calculate header’s height with help of systemLayoutSizeFittingSize:targetSize.

Returns the size of the view that satisfies the constraints it holds.
Determines the best size of the view considering all constraints it
holds and those of its subviews.

After changing header’s height it is necessary to reassign tableHeaderView property to adjust table cells.

Based on this answer: Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

- (void)sizeHeaderToFit
{
    UIView *header = self.tableView.tableHeaderView;

    [header setNeedsLayout];
    [header layoutIfNeeded];

    CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = header.frame;

    frame.size.height = height;
    header.frame = frame;

    self.tableView.tableHeaderView = header;
}

Leave a Comment