Search code examples
iosobjective-cuitableviewautolayoutmasonry-ios-osx

tableHeaderView on top of first cell


I'm trying to create a tableview programmatically that has a search bar in the tableHeaderView. For some reason the search bar appears on top of the first cell.

I'm using Masonry to build constraints.

Can someone point me to what i'm doing wrong.

- (void)setupViews {

...
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
    self.tableView.tableHeaderView = self.searchBar;
...
}

- (void)updateViewConstraints {

    [self.searchBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(@(44));
    }];

    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.self.top.equalTo(self.view);
        make.self.bottom.equalTo(self.toolbar.mas_top);
        make.width.equalTo(self.view);
    }];
...
}

Problem

You can see here that the header is at the same level as the cells. View hierarchy


Solution

  • Thanks for your help, I found a gist on GitHub which talked about changing the size of tableViewHeader using AutoLayout:

    https://gist.github.com/andreacremaschi/833829c80367d751cb83

    - (void) sizeHeaderToFit {
        UIView *headerView = self.tableHeaderView;
    
        [headerView setNeedsLayout];
        [headerView layoutIfNeeded];
        CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
        headerView.frame = ({
            CGRect headerFrame = headerView.frame;
            headerFrame.size.height = height;
            headerFrame;
        });
    
        self.tableHeaderView = headerView;
    }
    

    If I call this method during updateViewConstraints then it works.

    However, I don't fully understand it.