如何垂直居中两个视图并相对于超级视图平均划分宽度?
Posted
技术标签:
【中文标题】如何垂直居中两个视图并相对于超级视图平均划分宽度?【英文标题】:How to vertically center two views & divide the width equally relative to the super view? 【发布时间】:2015-06-10 11:35:23 【问题描述】:我正在尝试将两个Button
s 对齐到一个View
(以青色显示)。它们在View
中垂直对齐。当我尝试水平对齐它们时,它们的高度会改变。我希望它们的宽度应该根据超级视图的宽度相同,这与较小的 Next 按钮不同。这只能使用VFL
来实现吗?
代码如下:
[self prepareButton:saveButton label:@"SAVE"];
[buttonContainerView addConstraint:[NSLayoutConstraint constraintWithItem:saveButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:buttonContainerView
attribute:NSLayoutAttributeCenterY
multiplier:1.00f
constant:0]];
[saveButton layoutIfNeeded];
[self prepareButton:nextButton label:@"NEXT"];
[buttonContainerView addConstraint:[NSLayoutConstraint constraintWithItem:nextButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:buttonContainerView
attribute:NSLayoutAttributeCenterY
multiplier:1.00f
constant:0]];
[nextButton layoutIfNeeded];
[buttonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[saveButton]-[nextButton]-|"
options:0
metrics:metrics
views:viewDictionary]];
[saveButton layoutIfNeeded];
[nextButton layoutIfNeeded];
-(void)prepareButton:(UIButton *)button
label:(NSString *) label
[buttonContainerView addSubview:button];
button.translatesAutoresizingMaskIntoConstraints = NO;
button.backgroundColor = [UIColor redColor];
button.layer.cornerRadius = 2.50f;
[button setTitle:label forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
【问题讨论】:
【参考方案1】:通过在 VFL 中设置相等的高度和分配优先级解决了这个问题:
[buttonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[saveButton]-[nextButton(==saveButton@1000)]-|"
options:0
metrics:metrics
views:viewDictionary]];
【讨论】:
以上是关于如何垂直居中两个视图并相对于超级视图平均划分宽度?的主要内容,如果未能解决你的问题,请参考以下文章