我的视图如下图所示。我想将两个海军方块设置为具有相等的高度和宽度,然后灰色的中间条应填充剩余的空间。
我已经尝试在故事板模型中进行设置,但我无法使其正常工作。我对自动布局很新,并且喜欢关于如何使其工作的解释:)
答案 0 :(得分:2)
如果您只是将蓝色视图设置为三面拥抱容器并将其高度设置为相等,则布局模糊不清。有无限多的视图配置满足条件"蓝色视图是相等的高度,灰色视图占用其余部分"。您需要添加一个额外的约束 - 它可以是灰色视图的高度,或其中一个蓝色视图的高度或纵横比(在iOS 8上)。
更新:这里有一个如何使用Visual Format Language进行设置的示例:
NSDictionary *metrics = @{ @"grayHeight" : @30 };
NSDictionary *views = @{ @"topBlue" : topBlueView,
@"gray" : grayView,
@"bottomBlue" : bottomBlueView };
// First, set each view to hug its superview horizontally
[self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"|[topBlue]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"|[gray]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"|[bottomBlue]|" options:0 metrics:nil views:views]];
// Then, set the gray view to a fixed height and
// the blue ones to a variable height
[self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"V:|[topBlue][gray(grayHeight)][bottomBlue]|" options:0 metrics:metrics views:views]];
// Finally, set the top and bottom blue views to equal heights
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:topBlueView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:bottomBlueView
attribute:NSLayoutRelationHeight
multiplier:1
constant:0]]