From my testing, and this answer here, the UIView
returned from that method automatically has its origin set to (0, 0)
, its height set to the value returned from -tableView: heightForHeaderInSection:
and its width set to the width of the UITableView
.
I was able to add controls to that UIView
and even lay them out with auto layout without specifying any particular sizing in the init
method.
Here's my code to create the header view:
self.headerView = [[UIView alloc] init];
Here's the code where I lay out the controls inside the header view:
- (void)layoutControls {
[self.headerView addSubview:self.segmentedControl];
[self.headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[control]-(margin)-|"
options:0
metrics:@{@"margin": @(self.segmentedControlLeftRightMargin)}
views:@{@"control": self.segmentedControl}]];
[self.headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[control(==height)]"
options:0
metrics:@{@"margin": @(self.segmentedControlTopMargin),
@"height": @(self.segmentedControlHeight)}
views:@{@"control": self.segmentedControl}]];
[self.headerView addSubview:self.searchBar];
[self.headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[control]-(margin)-|"
options:0
metrics:@{@"margin": @(self.searchBarLeftRightMargin)}
views:@{@"control": self.searchBar}]];
[self.headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[control1]-(margin1)-[control2]-(margin2)-|"
options:0
metrics:@{@"margin1": @(self.segmentedControlBottomMargin),
@"margin2": @(self.searchBarBottomMargin)}
views:@{@"control1": self.segmentedControl,
@"control2": self.searchBar}]];
}
Here are the methods for the UITableViewDelgate
Protocol:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
// The hard-coded values are accurate for my controls, but you might need more advanced logic
return 44.0f + self.segmentedControlBottomMargin + 44.0f + self.searchBarBottomMargin;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return self.headerView;
}