從我的測試,這個答案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