Advanced Auto Layout:Programmatically Creating Constraints

Programmatically Creating Constraints以编程方式创建约束

Whenever possible, use Interface Builder to set your constraints. Interface Builder provides a wide range of tools to visualize, edit, manage, and debug your constraints. By analyzing your constraints, it also reveals many common errors at design time, letting you find and fix problems before your app even runs.

只要有可能,使用接口生成器来设置约束。接口生成器提供了多种工具来可视化、编辑、管理和调试约束。通过分析你的限制,它也揭示了许多常见的错误在设计时,让你发现和修复问题之前,你的应用程序甚至运行。

Interface Builder can manage an ever-growing number of tasks. You can build almost any type of constraint directly in Interface Builder (see Working with Constraints in Interface Builder). You can also specify size-class-specific constraints (see Debugging Auto Layout), and with new tools like stack views, you can even dynamically add or remove views at runtime (see Dynamic Stack View). However, some dynamic changes to your view hierarchy can still be managed only in code.

接口生成器可以管理越来越多的任务。可以在接口生成器中直接生成几乎任何类型的约束(参见与接口生成器中的约束一起工作)。还可以指定大小类特定的约束(参见调试自动布局),并使用新的工具(如堆栈视图),甚至可以在运行时动态添加或删除视图(参见动态堆栈视图)。但是,对视图层次结构的一些动态更改仍只能在代码中进行管理。

You have three choices when it comes to programmatically creating constraints: You can use layout anchors, you can use the NSLayoutConstraint class, or you can use the Visual Format Language. 

你有三个选择的时候,以编程方式创建约束:你可以使用布局的锚,你可以使用nslayoutconstraint类,或者你可以用视觉形式语言。

Layout Anchors布置锚

The NSLayoutAnchor class provides a fluent interface for creating constraints. To use this API, access the anchor properties on the items you want to constrain. For example, the view controller’s top and bottom layout guides have topAnchorbottomAnchor, and heightAnchor properties. Views, on the other hand, expose anchors for their edges, centers, size, and baselines.

nslayoutanchor类提供了用于创建约束界面流畅。若要使用此API,请访问要约束的项的锚属性。例如,视图控制器的顶部和底部布局指南topanchor,bottomanchor,和heightanchor性质。视图,另一方面,暴露锚的边缘,中心,大小和基线。
NOTE

In iOS, views also have layoutMarginsGuide and readableContentGuide properties. These properties expose UILayoutGuide objects that represent the view’s margins and readable content guides, respectively. These guides, in turn, expose anchors for their edges, centers, and size. 

在iOS中,观点也有layoutmarginsguide和readablecontentguide性质。这些特性使uilayoutguide对象表示视图的边缘和可读的内容指南,分别。这些指南,反过来,露出锚的边缘,中心和大小。

Use these guides when programmatically creating constraints to the margins or to readable content guides.

在编程时将约束创建到边距或可读内容指南时使用这些向导。

Layout anchors let you create constraints in an easy-to-read, compact format. They expose a number of methods for creating different types of constraints, as shown in Listing 13-1.

布局锚让您创建约束在一个易于阅读,紧凑格式。他们揭露了一些方法来创建不同类型的约束条件,如清单13-1所示。

Listing 13-1Creating layout anchors列表13-1creating布置锚

  1. // Get the superview's layout得到视图的布局
  2. let margins = view.layoutMarginsGuide
  3. // Pin the leading edge of myView to the margin's leading edge我想/销前缘到边缘的前缘
  4. myView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
  5. // Pin the trailing edge of myView to the margin's trailing edge我想/脚后缘后缘的边缘
  6. myView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true
  7. // Give myView a 1:2 aspect ratio给我的观点一方面比1:2
  8. myView.heightAnchor.constraintEqualToAnchor(myView.widthAnchor, multiplier: 2.0)

As described in Anatomy of a Constraint, a constraint is simply a linear equation.正如约束的解剖所描述的,约束仅仅是一个线性方程。

image: ../Art/view_formula.pdf

The layout anchors have several different methods for creating constraints. Each method includes parameters only for the elements of the equation that affect the results. So in the following line of code:布局锚有几种不同的方法来创建约束。每个方法仅包含影响结果的方程的元素的参数。所以在下面的代码行:

  1. myView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true

the symbols correspond to the following parts of the equation:符号对应于方程的下列部分:

 

Equation

Symbol

Item 1

myView

Attribute 1

leadingAnchor

Relationship

constraintEqualToAnchor

Multiplier

None (defaults to 1.0)

Item 2

margins

Attribute 2

leadingAnchor

Constant

None (defaults to 0.0)

The layout anchors also provides additional type safety. The NSLayoutAnchor class has a number of subclasses that add type information and subclass-specific methods for creating constraints. This helps prevent the accidental creation of invalid constraints. For example, you can constrain horizontal anchors (leadingAnchor or trailingAnchor) only with other horizontal anchors. Similarly, you can provide multipliers only for size constraints.

布局锚还提供额外的类型安全性。的nslayoutanchor类有若干子类,添加类型信息和特定的子类的方法创建约束。这有助于防止意外创建无效的约束。例如,你可以限制水平锚(leadinganchor或trailinganchor)只有与其他水平锚。类似地,可以只为大小约束提供乘法器。

NOTE

These rules are not enforced by the NSLayoutConstraint API. Instead, if you create an invalid constraint, that constraint throws an exception at runtime. Layout anchors, therefore, help convert runtime errors into compile time errors.

这些Rules are not enforced by the nslayoutconstraint API。相反,如果你创建一throws无效约束,约束,在运行时例外。锚杆布置,因此,帮助将运行时错误在编译时错误。

For more information, see NSLayoutAnchor Class Reference.更多信息,见nslayoutanchor类参考。

NSLayoutConstraint Class       nslayoutconstraint类

You can also create constraints directly using the NSLayoutConstraint class’s constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: convenience method. This method explicitly converts the constraint equation into code. Each parameter corresponds to a part of the equation (see The constraint equation).

你也可以直接使用nslayoutconstraint类的constraintwithitem约束:属性:relatedby:toitem:属性:乘数:常数:方便的方法。此方法显式地将约束方程转换为代码。每个参数对应于方程的一部分(见约束方程)。

Unlike the approach taken by the layout anchor API, you must specify a value for each parameter, even if it doesn’t affect the layout. The end result is a considerable amount of boilerplate code, which is usually harder to read. For example, the code in Listing 13-2 code is functionally identical to the code in Listing 13-1.

与布局锚点API所采取的方法不同,您必须为每个参数指定一个值,即使它不影响布局。最终的结果是大量的样板代码,这通常是难以阅读。例如,清单13-2代码的代码是在清单13-1代码功能相同

Listing 13-2Directly Instantiating Constraints列表13-2directly实例化约束

  1. NSLayoutConstraint(item: myView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .LeadingMargin, multiplier: 1.0, constant: 0.0).active = true
  2. NSLayoutConstraint(item: myView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .TrailingMargin, multiplier: 1.0, constant: 0.0).active = true
  3. NSLayoutConstraint(item: myView, attribute: .Height, relatedBy: .Equal, toItem: myView, attribute:.Width, multiplier: 2.0, constant:0.0).active = true

NOTE

In iOS, the NSLayoutAttribute enumeration contains values for the view’s margins. This means that you can create constraints to the margins without going through the layoutMarginsGuide property. However, you still need to use the readableContentGuide property for constraints to the readable content guides.

在iOS nslayoutattribute枚举值,包含在视图的边缘。这意味着你可以创建一个没有约束的边缘,通过layoutmarginsguide物业。然而,你仍然需要使用物业的readablecontentguide约束到可读的内容指南。

Unlike the layout anchor API, the convenience method does not highlight the important features of a particular constraint. As a result, it is easier to miss important details when scanning over the code. Additionally, the compiler does not perform any static analysis of the constraint. You can freely create invalid constraints. These constraints then throw an exception at runtime. Therefore, unless you need to support iOS 8 or OS X v10.10 or earlier, consider migrating your code to the newer layout anchor API.

不同的布局方法锚的API,方便不突出重要的特点一个特定的约束。As a result,它很容易错过重要的细节时,扫描过的代码。此外,编译器不会将任何静态分析的约束。你可以自由创建无效的约束。论文然后掷向约束在运行时异常。因此,除非你需要支持iOS和OS X的8 v10.10或更早,考虑升级到更新您的代码布局锚的API。

For more information, see NSLayoutConstraint Class Reference.更多信息,参考nslayoutconstraint湖等。

Visual Format Language视觉形式语言

The Visual Format Language lets you use ASCII-art like strings to define your constraints. This provides a visually descriptive representation of the constraints. The Visual Formatting Language has the following advantages and disadvantages:

可视格式语言允许您使用ASCII艺术像字符串来定义约束。这提供了一个直观的描述表示的约束。可视化格式语言有以下优点和缺点:

  • Auto Layout prints constraints to the console using the visual format language; for this reason, the debugging messages look very similar to the code used to create the constraints.自动布局使用视觉格式语言向控制台打印约束;因此,调试消息看起来与创建约束的代码非常相似。

  • The visual format language lets you create multiple constraints at once, using a very compact expression.可视化格式语言允许您使用一个非常紧凑的表达式立即创建多个约束。

  • The visual format language lets you create only valid constraints.可视格式语言只允许创建有效约束。

  • The notation emphasizes good visualization over completeness. Therefore some constraints (for example, aspect ratios) cannot be created using the visual format language.符号强调良好的可视化。因此,不能使用可视格式语言创建某些约束(例如,纵横比)。

  • The compiler does not validate the strings in any way. You can discover mistakes through runtime testing only.编译器不以任何方式验证字符串。只有通过运行时测试才能发现错误。

In Listing 13-1, the example has been rewritten using the Visual Format Language:在清单13-1,实例已被重写,以视觉形式语言:

Listing 13-3Creating constraints with the Visual Format Language列表13-3creating约束与视觉形式语言

  1. let views = ["myView" : myView]
  2. let formatString = "|-[myView]-|"
  3. let constraints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:.AlignAllTop , metrics: nil, views: views)
  4. NSLayoutConstraint.activateConstraints(constraints)

This example creates and activates both the leading and trailing constraints. The visual format language always creates 0-point constraints to the superview’s margins when using the default spacing, so these constraints are identical to the earlier examples. However, Listing 13-3 cannot create the aspect ratio constraint.

此示例创建并激活前向和后向约束。视觉形式语言总是0点约束视图的边缘使用默认间距时,那么这些约束对于之前的例子一样。然而,上市所不能创造的纵横比的约束。

If you create a more complex view with multiple items on a line, the Visual Format Language specifies both the vertical alignment and the horizontal spacing. As written, the “Align All Top” option does not affect the layout, because the example has only one view (not counting the superview).

如果在一行中创建多个视图的更复杂视图,则可视格式语言指定垂直对齐和水平间距。写,“对齐所有顶”选项不影响布局的例子,因为只有一个视图(不包括视图)。

To create constraints using the visual format language:使用可视格式语言创建约束:

  1. Create the views dictionary. This dictionary must have strings for the keys and view objects (or other items that can be constrained in Auto Layout, like layout guides) as the values. Use the keys to identify the views in the format string.茶字典创建的视图。必须有本字典字符串和对象(View for the Keys or other items that can be约束自动布局,布局指南类as the values)。使用the Keys to the视图来确定茶叶中的格式字符串。

    NOTE

    When using Objective-C, use the NSDictionaryOfVariableBindings macro to create the views dictionary. In Swift, you must create the dictionary yourself.

    当使用Objective-C,使用词典的宏观nsdictionaryofvariablebindings到创建视图。你必须创建在斯威夫特自己的字典。

  2. (Optional) Create the metrics dictionary. This dictionary must have strings for the keys, and NSNumberobjects for the values. Use the keys to represent the constant values in the format string.创建字典(optional)the计量。this dictionary for the strings must have for the keys,nsnumberobjects布尔值。表示方法使用the Keys the values in the format字符串常数。

  3. Create the format string by laying out a single row or column of items.通过创建单个行或列来创建格式字符串。

  4. Call the NSLayoutConstraint class’s constraintsWithVisualFormat:options:metrics:views:method. This method returns an array containing all the constraints.打电话给nslayoutconstraint类的constraintswithvisualformat:选项:标准:观点:方法。此方法返回包含所有约束的数组。

  5. Activate the constraints by calling the NSLayoutConstraint class’s activateConstraints: method.通过调用nslayoutconstraint类的activateconstraints激活约束方法。

For more information, see the Visual Format Language appendix.有关更多信息,请参见可视化格式语言附录。

iOS Android Appcan WeChat
原文地址:https://www.cnblogs.com/zyingn/p/AdvancedAutoLayout__ProgrammaticallyCreatingConstraints.html