自动布局 - 使视图的尺寸取决于另一个视图

时间:2013-12-09 16:57:31

标签: ios uikit autolayout

简单的交易:我想将UIView的宽度设为其超视图宽度的一半。这是我的代码:

//Display a red rectangle:
UIView *redBox = [[UIView alloc] init];
[redBox setBackgroundColor:[UIColor redColor]];
[redBox setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:redBox];

//Make its height equal to its superview's,
//minus standard spacing on top and bottom:
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[redBox]-|" options:0 metrics:nil views:@{@"redBox": redBox}];
[self.view addConstraints:constraints];

//Make its width half of its superviews's width (the problem):
NSLayoutConstraint *constraint = [NSLayoutConstraint
                                  constraintWithItem:redBox
                                  attribute:NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                                  attribute:NSLayoutAttributeWidth
                                  multiplier:0.5
                                  constant:0.0
                                  ];

[self.view addConstraint:constraint];

[self.view setBackgroundColor:[UIColor blueColor]];

这就是我得到的:

enter image description here

如果我将multiplier设置为1.0,则视图的宽度是其超级视图的一半。但那是为什么呢?

1 个答案:

答案 0 :(得分:1)

问题可能是您的红框视图受限制不足。你给它一个宽度,但没有什么可以告诉它应该在哪里水平放置。因为它应该是superview的宽度的一半,所以它可以选择将自己定位在superview的左半部分。或右半边。或中间。你没有指定,所以框架只是选择了一些东西。

在这种情况下,看起来它选择将红色框的 center 与superview的左边缘对齐。这似乎是一个奇怪的选择,但同样,你没有指定任何东西。它可以随心所欲地选择它。

添加另一个将水平定位视图的约束。这应该可以解决问题。