中心视图使用* only * visual format?

时间:2014-12-02 20:27:20

标签: ios visual-format-language

我试图将两个不同高度的视图垂直居中。

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

这可以使两个中心垂直对齐,但它们位于超视图的底部! enter image description here

我想垂直居中,不仅相对于彼此,也在超视图中。

我添加了这样的约束,它可以工作:

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

enter image description here

但我想知道,这是否有可能只使用可视化格式?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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]];