【发布时间】:2013-12-09 16:57:30
【问题描述】:
简单的交易:我想将 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]];
这是我得到的:
如果我将multiplier 设置为1.0,则视图的宽度是其父视图的一半。但这是为什么呢?
【问题讨论】:
-
在
self.view上设置背景颜色可能很有用,只是为了确保它也是您期望的大小。 -
完成,我更新了问题和截图。这是一个新的 UIViewController,所以
self.view应该有默认尺寸。 -
这段代码在哪里调用?视图加载?一个单独的方法?如果在 viewDidLoad 之后调用,请尝试调用 [self.view layoutIfNeeded]。
-
是的,它在
viewDidLoad中调用。我试过打电话给[self.view layoutIfNeeded],但没有帮助。如果您将其复制并粘贴到空 ViewController 的viewDidLoad中,您应该会得到相同的结果。 -
layoutIfNeeded应该不是必需的,因为只要添加了约束,视图就会自动再次运行布局。
标签: ios uikit autolayout