翻译@Auto Layout Guide(自动布局指南)
Appendix(附录)
Visual Format Language(视觉格式化语言)
本文讲解如何使用Visual Format Language(视觉格式化语言,以下简称VFL)创建常见约束,包括但不限于标准间距约束,尺寸约束,垂直约束,以及优先级各异的约束;更有完整的VFL语法规则供参考。
Visual Format Syntax(用VFL描述约束)
以下例子示范如何通过VFL表示各种约束。请特别注意图片中约束关系是如何通过VFL描述的。
标准间距约束
[button]-[textField]

宽度约束
[button(>=50)]

相对父视图边缘约束
|-50-[purpleBox]-50-|

垂直约束
V:[topField]-10-[bottomField]

同级视图约束
[maroonView][blueView]

明确约束优先级
[button(100@20)]

等宽约束
[button1(==button2)]

多条件约束
[flexibleButton(>=70,<=100)]

一次性定义多个约束
|-[find]-[findNext]-[findField(>=20)]-|

VFL强调约束的清晰表达,能够创建大部分常用约束。但某些约束,如宽高比(如imageView.width = 2 * imageView.height),无法使用VFL表示。这时只能选择使用约束方法constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:。
Visual Format String Grammar(VFL详细语法)
编写VFL字符串时,完整语法规则如下(字面量以高亮显示,e代表空字符串)。
| 符号 | 替换规则 | ||
|---|---|---|---|
| \ |
(\ (\ \ (\ |
||
| \ |
H\ |
V |
|
| \ |
|||
| \ |
[\] |
||
| \ |
e\ | -\ |
- |
| \ |
\ |
\ |
|
| \ |
\ |
\ |
|
| \ |
(\ |
||
| \ |
(\ |
||
| \ |
==\ |
<=\ |
>= |
| \ |
\ |
\ |
|
| \ |
\ |
\ |
|
| \ |
\ |
\ |
|
| \ |
作为C符号解析。必须是视图字典中的一个key,对应一个NSView对象。 |
||
| \ |
作为C符号解析。必须是数量字典中的一个key,对应一个NSNumber对象。 |
||
| \ |
根据C语言本地化配置,使用strtod_l解析(将ASCII字符串转化为浮点数)。 |
注意
对于
objectOfPredicate来说,如果条件同视图宽高相关,则接受viewName作为参数。也就是说,可以通过[view1(==view2)]的形式规定view1和view2等宽。
如果出现句法错误,则程序抛出异常,同时输出诊断信息。例如:
Expected ':' after 'V' to specify vertical arrangementV|[backgroundBox]|^A predicate on a view's thickness must end with ')' and the view must end with ']'|[whiteBox1][blackBox4(blackWidth][redBox]|^Unable to find view with name blackBox|[whiteBox2][blackBox]^Unknown relation. Must be ==, >=, or <=V:|[blackBox4(>30)]|^
