从我的测试,这个答案here,从方法自动的原点设置为(0, 0)
返回UIView
,其高度设置为设置的宽度从-tableView: heightForHeaderInSection:
,其宽度返回的值UITableView
。
我能够将控件添加到该UIView
甚至没有在init
方法中指定任何特定的大小自动布局。
这里是我的代码来创建头视图:
self.headerView = [[UIView alloc] init];
这里就是我躺在了头视图中的控件代码:
- (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}]];
}
下面是对UITableViewDelgate
协议的方法:
- (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;
}
谢谢,我学到了东西,返回一个zerorect视图使用正确的完整大小,所以不需要使用tableview.bounds,但是这在旋转时不正确。你必须重新加载tableview。我猜测没有超级视图来贴近边缘。 – Darren
是的,它似乎被视为“超出了自动布局的界限”。当我在过去需要这种行为时,我实际上已经对UITableViewCell进行了子类化,并使用它来代替节头。如果实际使用段,它可能只是行0(零)的单元格。这样,你** **得到旋转支持。 – mbm29414
这实际上不是一个坏主意。实际上,当表格滚动时,也会停止屏幕标题停留在屏幕上。 – Darren