ios - 为什么这不足以添加一个 View 以使用自动布局占据所有屏幕?

标签 ios objective-c cocoa-touch uiview autolayout

我不明白为什么这对添加 subview 不起作用。

UIView *orangeView = [[UIView alloc] init];
orangeView.translatesAutoresizingMaskIntoConstraints = NO;
orangeView.backgroundColor = [UIColor orangeColor];

[self.view addSubview:orangeView];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];

我没有收到任何错误或警告,但 View 没有显示。

最佳答案

您正在向 self.view 添加约束,使 self.viewself.view 具有相同的尺寸。添加约束时永远不要使用 orangeView

将您的代码更改为:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:orangeView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:orangeView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:orangeView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:orangeView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];

关于ios - 为什么这不足以添加一个 View 以使用自动布局占据所有屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22002489/

相关文章:

ios - NSPredicate/TableView 只显示一项,为什么?

iphone - iPhone 上的最佳 SQLite 实践

ios - iphone 应用程序尺寸小于屏幕

ios - NSDictionary 初始化(contentsOfFile :) is deprecated so now what?

ios - 访问同一个类的另一个接口(interface)中的方法

objective-c - UITableView 自定义 UIView 重复

ios - 如何计算给定一系列数字的一些点

iphone - cocoa 中的小写 "k"

iphone - UISegmentedController 中的图标和文本

ios - 如何检测用户在 SKStoreReviewController 上点击了哪个按钮?