我正在尝试将 2 个不同高度的 View 垂直居中。
UILabel *view1 = [[UILabel alloc] init];
view1.backgroundColor = [UIColor redColor];
view1.text = @"view1\nline2";
view1.textAlignment = NSTextAlignmentCenter;
view1.numberOfLines = 0;
UILabel *view2 = [[UILabel alloc] init];
view2.backgroundColor = [UIColor greenColor];
view2.text = @"view2\nline2";
view2.textAlignment = NSTextAlignmentCenter;
view2.numberOfLines = 0;
[self.view addSubview:view1];
[self.view addSubview:view2];
NSDictionary *views = @{@"view1": view1, @"view2" : view2};
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
for (UIView *view in views.allValues) {
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[view1]-[view2(==view1)]-|"
options:NSLayoutFormatAlignAllCenterY
metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=20)-[view1(200)]-(>=20)-|"
options:NSLayoutFormatAlignAllCenterY
metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=20)-[view2(100)]-(>=20)-|"
options:NSLayoutFormatAlignAllCenterY
metrics:nil views:views]];
这设法使两者的中心垂直对齐,但它们位于父 View 的底部!
我不仅要相对于彼此垂直居中,还要在父 View 中垂直居中。
我添加了这样的约束并且它起作用了:
[self.view addConstraint:
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0]];
但是我想知道,仅使用视觉格式是否可以实现?
最佳答案
是的,这是可能的,但只能通过添加间隔 View 。所以如果你创建了几个 View ,我们称它们为 spacer1 和 spacer2,你可以用这个字符串将 view1 居中,
@"V:|[spacer1][view1][spacer2(==spacer1)]|"
这假定 view1 具有固定高度。不过,我不建议这样做,我只会使用您在帖子底部显示的代码。
关于ios - 中心 View 使用*仅*视觉格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258312/