ios - 中心 View 使用*仅*视觉格式?

标签 ios visual-format-language

我正在尝试将 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 的底部! enter image description here

我不仅要相对于彼此垂直居中,还要在父 View 中垂直居中。

我添加了这样的约束并且它起作用了:

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

enter image description here

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

最佳答案

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

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

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

关于ios - 中心 View 使用*仅*视觉格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258312/

相关文章:

ios - 重复符号 '_lprofMergeValueProfData'

ios - 什么时候需要标签和按钮的内容拥抱以防止它们占用文本字段的空间?

ios - 使用 Autolayout Visual Format Language 将 UIViews 排成一行

swift - 视觉格式语言中的水平居中

ios - 使用自动布局视觉格式语言是否可以将 View 的宽度设置为等于同一 View 的高度?

ios - 使用自动布局和 NSLayoutConstraints 以编程方式检索 UIView 的宽度和高度?

objective-c - 为 Core Plot 触摸事件访问数据数组时崩溃

ios - 互联网连接丢失时使用自定义 REST API 同步来自核心数据的数据?

iphone - 如何以编程方式更改应用程序语言而不重新启动我的应用程序?

ios - 如何在 Swift 中使用扩展协议(protocol)公开 Obj-C 类的现有属性