gpt4 book ai didi

ios 自动布局视觉格式 - 对齐

转载 作者:行者123 更新时间:2023-12-03 16:20:24 28 4
gpt4 key购买 nike

在 iOS6 中,我使用自动布局。

  • 我有 2 个以编程方式创建的 View v1 和 v2。
  • v2 作为 subview 添加到 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 将其高度和宽度拉伸(stretch)到其 super View 的大小(在本例中为 v1)并将其定位在其 super View 的右侧。

看来在你的情况下,你不需要对齐 View centerX和centerY。否则,我无法正确理解您问题的上下文。

关于ios 自动布局视觉格式 - 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12695222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com