ios - 如何使用自动布局正确约束 UITableView

标签 ios objective-c uitableview autolayout

我想放置一个 UITableView,使其占据我的 View Controller 的一个 subview 的全部。这是 View 层次结构,其中 self 是我的 UIViewController 子类:

[self.view] -> [self.rootView] -> [self.tableView]

我知道我需要将 setTranslatesAutoresizingMaskIntoConstraints 设置为 NO 对于我想使用自动布局布局其 subview 的任何 View ,所以这是我的 viewDidLoad.

[super viewDidLoad];
self.rootView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 568.0)];
[self.rootView setTranslatesAutoresizingMaskIntoConstraints:NO];

到目前为止一切顺利。现在我想添加一个 UITableView。

self.tableView = [[UITableView alloc]init]; // same thing with initWithFrame:CGRectZero
[self.rootView addSubview:self.tableView];

到目前为止没有问题,但我看不到表格 View (因为它没有框架)。让我们添加一些约束:

[self.rootView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[table]-0-|" options:0 metrics:nil views:@{@"table": self.tableView}]];
[self.rootView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[table]-0-|" options:0 metrics:nil views:@{@"table": self.tableView}]];

一切都崩溃了。 self.rootView.backgroundColor 是绿色的,单元格是蓝色的,全是文字,但是屏幕上除了灰色什么都没有,可能表明 self.view 已经不在了 View 层次结构?我做了很多谷歌搜索,但无法在任何地方找到真正的解决方案。我还尝试以另一种方式一次添加所有约束,同样的事情发生了。有人有什么想法吗?

最佳答案

我认为您应该在 UITableView 而不是 self.rootView 上调用 setTranslatesAutoresizingMaskIntoConstraints:NO。但正如 rdelmar 评论的那样,首先要确保你的表格 View 不是你在灰色背景下看到的,因为它会填满屏幕并覆盖其他 View 。

还有一点,我相信上面的self.rootView = [[UIViewController alloc]initWithFrame...] 实际上应该是[[UIView alloc] initWithFrame...] 因为 Controller 没有框架,但上面可能只是不正确,因为这会在尝试运行时导致错误。

关于ios - 如何使用自动布局正确约束 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24023090/

相关文章:

ios - 如何使用#keyPath 使用 swift 4 排序方法

ios - ScrollView 分页,图像稍微向左或向右显示(开始/结束)

iphone - 注册地址簿更改,使用 ABAddressBookRegisterExternalChangeCallback

ios - 从 NSURLConnection 到 NSURLSession

Swift TableView 对图像发出多个网络请求

ios - SwiftUI:如何将核心数据对象传递给 View ?

ios - 使用 UIGestureRecogniser 子类化时未调用 Touches Ended

ios - 带约束的嵌套 Collection View 的意外行为 (Swift 4)

ios - 自定义单元格图像在 UITableView 中自行更改

objective-c - Xcode - 在我的应用程序中实现网络错误警报?不能让它工作?