[英]NSLayoutConstraint and “attach” two labels to each other
我有两个标签。 如果移动一个,我希望能够移动它们。 如何将它们与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] - | ........................... .................................................. .............................. ^”
w / out NSLayoutFormatAlignAllBaseline选项,它运行正常(它们堆栈但不是全部水平居中)。
如果需要在代码中执行此操作,请首先创建NSLayoutConstraint,然后将约束添加到标签的superview。
有两种方法可以在代码中创建约束。 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) ] ;
然后将约束添加到标签的superview:
[label1.superview addConstraints:constraints] ; // Use `label1.superview` or your own reference to the label's superview.
Cocoa自动布局指南简短易懂。 给它一个阅读,我很乐意回答你还有的任何问题。
编辑1
选项NSLayoutFormatAlignAllBaseline
创建约束(除了由NSLayoutFormatAlignAllBaseline
创建的约束),这些约束垂直对齐所有指定对象的基线。 如果您的VisualFormat字符串正在创建垂直约束(它以“V:”开头),则您不想使用此选项。 您希望使用0(表示没有选项)或创建水平约束的选项,如NSLayoutFormatAlignAllCenterX。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.