Adding constraint to a UITableVIew headerview

让人想犯罪 __ 提交于 2019-11-30 21:17:34

When you are adding a view as a header or footer to the table view, you cannot use constraints on this view, but only inside it. Also the view must be on the top of the hierarchy (as you have), if you move it as a subview to another view, it will give the same error.

You can change view's height directly in code by setting the same frame with changed height. This is working fine.

Also remember that this changes will not apply until you reassign the header:

tableView.tableHeaderView.frame = ...;
tableView.tableHeaderView = tableView.tableHeaderView;

I had the same issue, I couldn't use constraints on the tableHeaderView.

Then I created another subView to create the constraints into.

// 1 - create a header view and a subHeaderView
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, bounds.size.height - 64.f)];
headerView.backgroundColor = [UIColor blackColor];

tableView.tableHeaderView = headerView;

UIView *subHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, bounds.size.height - 64.f)];
[headerView addSubview:subHeaderView];

// 2 - add constrainedView to subHeaderView (E.g.)
UIView *constrainedView = [UIView new];
[constrainedView setTranslatesAutoresizingMaskIntoConstraints:NO];
[subHeaderView addSubView:constrainedView];

// 3 - addConstraints of subviews into subHeaderView (E.g.)
[subHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[constrainedView]|" options:0 metrics:metrics views:views]];
[subHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[constrainedView]|" options:0 metrics:metrics views:views]];

This is working on my project, iOS 7.0 / Xcode 5.0.2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!