在ios6中,我正在使用autolayouts。

  • 我有2次视图v1和v2编程创建。
  • V2作为子视图添加到V1
  • 已经编程地创建了V1的约束(此处未显示)。
  • 我想要v1和v2的大小相同,我希望v2放在V1的顶部,恰好水平和垂直中心匹配,使得V2完全位于V1
  • 顶部。

问题:

  • 如何实现这一目标(最好使用可视格式,如果您无法建议替代方法)?

代码 - 下面给出我的尝试,但它不提供所需的输出。 - 没有抛出错误。V1正确放置,但V2是V1

的左侧角落

注 - 我在评论中解释了,我想做什么。

[v1 addSubView:v2];

v1.translatesAutoresizingMaskIntoConstraints        = NO;
v2.translatesAutoresizingMaskIntoConstraints        = NO;

NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(v1,
                                                              v2);

//I wanted v1 and v2 to be of the same height and wanted the center Y to be aligned together
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[v2(==v1)]"
                                                                         options:NSLayoutFormatAlignAllCenterY
                                                                         metrics:nil
                                                                           views:viewDictionary];


//I wanted v1 and v2 to be of the same height and wanted the center X to be aligned together
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[v2(==v1)]"
                                                                       options:NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:viewDictionary];

[v1 addConstraints:horizontalConstraints];
[v1 addConstraints:verticalConstraints];
.

有帮助吗?

解决方案

不应该只是这项工作?

NSMutableArray *constraints = [NSMutableArray new];

constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[v2]|"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:NSDictionaryOfVariableBindings(v2)];
constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[v2]|"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:NSDictionaryOfVariableBindings(v2)];
[v1 addConstraints:constraints];
.

这是什么,它使V2将其高度和宽度拉伸到其超级尺寸,在这种情况下,在这种情况下是V1,并将其定位在其超顶部。

似乎在您的情况下,您不需要对齐视图中心x和中心。否则,我不正确地理解你的问题的背景。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top