了解iOS中的可视格式约束目标C.

时间:2017-11-20 11:19:19

标签: ios objective-c nslayoutconstraint

我知道在 InterfaceBuilder ex中设置约束。前导,尾随,顶部,底部,固定宽度等。 我发现了一些约束代码,我不知道这个代码试图设置哪个约束,下面的视觉格式约束究竟是什么意思?

  NSDictionary *binding = @{@"v" : self.view};
    NSDictionary *metrics = @{@"height" : @(self.height)};
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[v]|" options:0 metrics:nil views:binding]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[v(==height)]|" options:0 metrics:metrics views:binding]];

2 个答案:

答案 0 :(得分:2)

  

H:| [V] |

H表示约束是水平添加的,类似V表示垂直。

|表示绑定字典所指示的超级视图。 NSDictionary *binding

[v]代表视图本身。

所以H:|[v]|解析为领先& 0常量的尾随约束。

  

N:[V(==高度)] |

此处类似,视图给出了一个底部约束和一个带height常量NSDictionary *metrics的高度约束。

有关详细信息,请参阅https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html

答案 1 :(得分:0)

正如GoodSp33d向我建议的那样。

你的约束是 -

(1)领先& 尾随 self.view 0 我已将上述约束转换为不同的方式

(2) ContentView的底部分配给 self.view

(3)恒定高度约束

以另一种形式约束 -

    [self.contentView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
    [self.contentView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
    [self.contentView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;


    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.view
                                                                        attribute:NSLayoutAttributeHeight
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:nil
                                                                        attribute:NSLayoutAttributeNotAnAttribute
                                                                       multiplier:1.0
                                                                         constant:self.height];
    [self.view addConstraint:heightConstraint];