了解 iOS Objective C 中的视觉格式限制

Understanding visual format constraints in iOS Objective C

我知道在 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]];

H:|[v]|

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

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

[v] 表示视图本身。

因此 H:|[v]| 解析为 0 常量的前导和尾随约束。

V:[v(==height)]|

类似地,视图被赋予底部约束和高度约束,如NSDictionary *metrics中所述,常数height

更多信息请参考https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html

正如 GoodSp33d 向我建议的那样。

你的约束是-

(1) 前导 & 尾随self.view0 我已将上述约束转换为不同的方式

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