原文链接:https://developer.apple.com/……/AutolayoutPG/AutoLayoutinCode/AutoLayoutinCode.html
自动布局编程(Working with Auto Layout Programmatically)
虽然Interface Builder中提供了一个方便的可视化界面用于自动布局工作,你可以通过代码创建,添加,删除约束。例如,如果你在运行是添加或删除视图,你将需要通过代码添加约束,以确保你的接口能够正确的改变大小或方向。
以编程方式创建约束(Creating Constraints Programmatically)
你可以通过实例NSLayoutConstraint来代表
约束,通常使用constraintsWithVisualFormat:options:metrics:views:来创建约束。
这种方法的第一个参数是可视化格式字符串( visual format string),你想描述的布局提供了一个可视化表示。这种可视化格式语言被设计成尽可能地易读;视图在方括号中表示,视图和视图之间的连接使用连字符表示(或两个连字符分隔的数字代表视图之间的分割)。更多的例子和可视化格式语言学习语法,请参阅“Visual Format Language.”
作为一个例子,你可能代表两个按钮之间的约束:
使用下面的可视化格式字符串:
[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];
安装约束(Installing Constraints)
为了使约束有效,你必须添加到一个视图。被约束的视图必须是它的一个祖先,通常应该是最近的共同祖先。(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翻译,转载请注明出处,谢谢!