1

我正在尝试将 2 个不同高度的视图垂直居中。

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]];

这设法使两者的中心垂直对齐,但它们位于超级视图的底部! 在此处输入图像描述

我不仅要相对于彼此垂直居中,还要在超级视图中垂直居中。

我添加了这样的约束并且它有效:

[self.view addConstraint:
 [NSLayoutConstraint constraintWithItem:view1
                              attribute:NSLayoutAttributeCenterY
                              relatedBy:NSLayoutRelationEqual
                                 toItem:self.view
                              attribute:NSLayoutAttributeCenterY
                             multiplier:1
                               constant:0]];

在此处输入图像描述

但我想知道,这是否可以仅使用视觉格式来实现?

4

2 回答 2

2

是的,这是可能的,但只能通过添加间隔视图。因此,如果您创建了几个视图,我们称它们为 spacer1 和 spacer2,您可以使用此字符串将 view1 居中,

@"V:|[spacer1][view1][spacer2(==spacer1)]|"

这假设 view1 具有固定的高度。不过,我不建议这样做,我只会使用您在帖子底部显示的代码。

于 2014-12-02T20:37:27.070 回答
0

计算“指标”中的 Y 怎么样?

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-centerY-[view1(200)]-(>=20)-|"
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:@{@"centerY": @(CGRectGetHeight(self.view.frame)/2.0 - 100)}
                                                                    views:views]];
于 2014-12-02T20:57:45.347 回答