Dar*_*ren 5 objective-c uitableview ios autolayout
我正在使用UITableView委托方法viewForHeaderInSection在我的提供节标题UITableView.
我最初创建一个这样的视图:
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 50)];
Run Code Online (Sandbox Code Playgroud)
然后使用Autolayout添加一些子视图,然后返回 headerView
我遇到的问题是我不想具体指定headerView大小.我想使用Autolayout将左右边缘固定到视图的宽度.这是问题,我没有在Autolayout代码中使用的superview.
使用上面的代码,意味着标题视图不会在旋转时自动调整大小.您必须在轮换后重新加载tableview.
我有什么想法可以设置headerView它的边缘到tableview?
谢谢
根据我的测试以及此处的答案,UIView从该方法返回的值自动将其原点设置为(0, 0),将其高度设置为从返回的值-tableView: heightForHeaderInSection:,并将其宽度设置为 的宽度UITableView。
我能够向其中添加控件UIView,甚至使用自动布局来布局它们,而无需在init方法中指定任何特定的大小。
这是我创建标题视图的代码:
self.headerView = [[UIView alloc] init];
Run Code Online (Sandbox Code Playgroud)
这是我在标题视图中布置控件的代码:
- (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}]];
}
Run Code Online (Sandbox Code Playgroud)
以下是该协议的方法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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2495 次 |
| 最近记录: |