4

我有两个标签。如果一个被移动,我希望能够同时移动两者。我如何将它们与 NSLayoutConstraints “附加”在一起?我可以在 IB 中做到这一点,但需要在代码中做到这一点。

另外,什么是 NSLayoutAttributeBaseline、NSLayoutAttributeLeading 和 NSLayoutAttributeTrailing?

编辑:

居中poweredByLabel(又名label02):

[constraints addObject:[NSLayoutConstraint constraintWithItem:poweredByLabel
                                                    attribute:NSLayoutAttributeCenterX
                                                    relatedBy:NSLayoutRelationEqual
                                                       toItem:myImage
                                                    attribute:NSLayoutAttributeCenterX
                                                   multiplier:1.0
                                                     constant:0]];

堆叠标签并垂直切换:

[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[rememberPasswordSwitch]-10-[rememberPasswordLabel]-10-[versionLabel]-[poweredByLabel]-|"
                                                                         options:NSLayoutFormatAlignAllBaseline
                                                                         metrics:nil
                                                                           views:viewsDictionary]];

这会产生错误:

*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法解析约束格式:选项掩码需要在垂直边缘对齐的视图,这对于也是垂直的布局是不允许的。五:[rememberPasswordSwitch]-10-[rememberPasswordLabel]-10-[versionLabel]-[poweredByLabel]-|............ ..................................................... ....................^'

没有 NSLayoutFormatAlignAllBaseline 选项,它运行良好(它们堆叠但并非全部水平居中)。

4

1 回答 1

7

如果您需要在代码中执行此操作,请首先创建 NSLayoutConstraint(s),然后将约束添加到标签的超级视图。

有两种方法可以在代码中创建约束。constraintsWithVisualFormat通常比 . 简洁得多constraintWithItem

// Make label1's NSLayoutAttributeTrailing be the 'standard Aqua space' away from label2's NSLayoutAttributeLeading. Also, vertically align their baselines.
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[label1]-[label2]"  options:NSLayoutFormatAlignAllBaseline  metrics:nil  views:NSDictionaryOfVariableBindings(label1, label2) ] ;

然后将约束添加到标签的超级视图:

[label1.superview  addConstraints:constraints] ;   // Use `label1.superview` or your own reference to the label's superview.

Cocoa 自动布局指南简短易懂。读一读,我很乐意回答您仍有的任何问题。

编辑 1

该选项NSLayoutFormatAlignAllBaseline创建垂直对齐所有指定对象的基线的约束(除了由 VisualFormat 字符串创建的约束)。如果您的 VisualFormat 字符串正在创建垂直约束(它以“V:”开头),您不想使用此选项。您可能想使用 0(这意味着没有选项)或创建水平约束的选项,例如 NSLayoutFormatAlignAllCenterX。

于 2013-01-09T19:36:39.890 回答