Davis Davis - 6 months ago 47
iOS Question

tableHeaderView with Autolayout not working correctly

Hey everybody i have a TableHeaderView and everything gets managed by Autolayout:

  • The
    at the top should be always 2:1, so i set the Aspect ration and the Rest of the needed Constraints.

  • The 4
    should be always horizontal and should have the same Height and Width. So i worked with Equal Width and Equal Height and also with a Aspect Ratio of 1:1

  • And i have two
    set to 0. I also made a Subclass of my
    , because of the
    , like this:

    - (void) layoutSubviews
    [super layoutSubviews];

    if ( self.numberOfLines == 0 )
    if ( self.preferredMaxLayoutWidth != self.frame.size.width )
    self.preferredMaxLayoutWidth = self.frame.size.width;
    [self setNeedsUpdateConstraints];

This is my Code:

- (void)initializeHeaderViewLabels
//After the Response from my server arrived i set the tableHeaderView with the Textdata
self.tableView.tableHeaderView = nil;

if((self.contentDict[@"title"]) != [NSNull null])
self.headerTitleLabel.text = (self.contentDict[@"title"]);

if((self.contentDict[@"shortDescription"]) != [NSNull null])
self.headerDescriptionLabel.text = (self.contentDict[@"shortDescription"]);

[self.headerView setNeedsLayout];
[self.headerView layoutIfNeeded];

CGFloat height = [self.headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

CGRect headerFrame = self.headerView.frame;
headerFrame.size.height = height;
self.headerView.frame = headerFrame;

[self.tableView setTableHeaderView:self.headerView];


I get my Image and the Text for the
from my Server, so i have to wait until the Response arrives, then i call

**My Problem is that the tableHeaderView is way too large during Runtime and so my UILabels get stretched and there is a lot of whiteSpace. Maybe i miss something?


In order to make it work you'll need some magic or migrate away from table header view. I've already answered on a similar question here. The trick is to magically reset tableHeaderView after evaluating it's height via autolayout. I've created sample project for that: TableHeaderView+Autolayout.