NSLayoutConstraint来代表
约束,通常使用constraintsWithVisualFormat:options:metrics:views:来创建约束。
使用下面的可视化格式字符串:
[button1]-12-[button2] |
一个连字符表示标准的水空间(Aqua space),所以你也可以代表这样的关系:
[button1]-[button2] |
View的名字来自视图字典---键是格式字符串中使用的名称,值是对应的视图对象。为方便起见,NSDictionaryOfVariableBindings
创建一个字典,其中键是和相应值的变量名一样。创建约束的代码变为:
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(self.button1, self.button2); NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[button1]-[button2]" options:0 metrics:nil views:viewsDictionary];
The visual format language prefers good visualization over completeness of expressibility.虽然大多数的约束,在真实的用户界面是有用的,可以使用代码表示,有些却不能。一个有用的约束,该约束也无法表达的是一个固定的纵横比(例如,imageView.width = 2 * imageView.height
)。要创建这样一个约束,你可以使用
constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:
作为一个例子,你也可以使用这种方法来创建较早的[button1]-[button2]的
约束:
[NSLayoutConstraint constraintWithItem:self.button1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.button2 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:-12.0];
为了使约束有效,你必须添加到一个视图。被约束的视图必须是它的一个祖先,通常应该是最近的共同祖先。(This is in the existing NSView
API sense of the word ancestor, where a view is an ancestor of itself。)约束在这个视图的坐标系中被解读。
假设您安装[zoomableView1] -80 - [zoomableView2]
的共同祖先zoomableView1
和zoomableView2
。
值80看起来就像是在容器的坐标系统,如果你绘制的约束。
如果任一可缩放视图边界的变换被变化了,它们之间的空间保持固定。
如果容器的边界变换本身改变了,空间间隔也会改变。
NSView
提供一种方法addConstraint:来
添加约束,删除或检查现有的约束removeConstraint
:和constraints
,以及其他相关的方法。NSView 还提供了一种方法,这是类似的sizeToFit
方法NSControl里的fittingSize
,
但对于任意的视图,而不是控制。
fittingSize
方法返回视图理想的大小,only those constraints installed on the receiver’s subtree together with a preference for the view to be as small as possible。一般意义上基于约束的系统里fitting size 并不是“最好”的尺寸,视图的“最好”的大小(如果你考虑一切)是定义其当前大小。
Copyright © 2013 Apple Inc. All Rights Reserved.Terms of Use|Privacy Policy| Updated: 2013-09-18
TheLittleBoy翻译,转载请注明出处,谢谢!