【发布时间】:2014-08-15 15:16:26
【问题描述】:
我以编程方式创建了一个 UIButton 并将其添加到这样的视图中:
self.button = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 100, 30)];
[self.button setTitle:@"Test" forState:UIControlStateNormal];
self.button.translatesAutoresizingMaskIntoConstraints = YES;
[myView addSubview:self.button];
按钮显示正确,并且不使用其固有大小(这是正确的,因为 translatesAutoresizingMaskIntoConstraints 已打开)。但是,当我打印出 myView.constraints 时,我看不到有关按钮的任何约束。根据定义,当 translatesAutoresizingMaskIntoConstraints 打开时,将自动生成约束并添加到超级视图,在本例中为 myView。
那么为什么这里没有生成约束呢?为什么布局系统仍然知道如何在屏幕上布局按钮?
********更新: 我想我知道原因。 当 UIView 没有附加任何约束时,布局系统将不会到位。它将使用视图的框架。 在这种情况下,当我们打开 translatesAutoresizingMaskIntoConstraints 时,不会生成按钮的内在约束,因此按钮没有任何约束。因此将使用框架。 从代码创建的所有 UIView 都将 translatesAutoresizingMaskIntoConstraints 默认为 YES,因此不会为视图自动生成约束。框架将被使用。这对于向后兼容非常有意义。
【问题讨论】:
-
您还有哪些使用自动布局的视图?
-
主视图从 nib 加载,它使用 AutoLayout。
标签: ios autolayout programmatically-created