翻译@Auto Layout Guide(自动布局指南)


Appendix(附录)

Visual Format Language(视觉格式化语言)

本文讲解如何使用Visual Format Language(视觉格式化语言,以下简称VFL)创建常见约束,包括但不限于标准间距约束,尺寸约束,垂直约束,以及优先级各异的约束;更有完整的VFL语法规则供参考。

Visual Format Syntax(用VFL描述约束)

以下例子示范如何通过VFL表示各种约束。请特别注意图片中约束关系是如何通过VFL描述的。

标准间距约束

  1. [button]-[textField]

图70

宽度约束

  1. [button(>=50)]

图71

相对父视图边缘约束

  1. |-50-[purpleBox]-50-|

图72

垂直约束

  1. V:[topField]-10-[bottomField]

图73

同级视图约束

  1. [maroonView][blueView]

图74

明确约束优先级

  1. [button(100@20)]

图75

等宽约束

  1. [button1(==button2)]

图76

多条件约束

  1. [flexibleButton(>=70,<=100)]

图77

一次性定义多个约束

  1. |-[find]-[findNext]-[findField(>=20)]-|

图78

VFL强调约束的清晰表达,能够创建大部分常用约束。但某些约束,如宽高比(如imageView.width = 2 * imageView.height),无法使用VFL表示。这时只能选择使用约束方法constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:

Visual Format String Grammar(VFL详细语法)

编写VFL字符串时,完整语法规则如下(字面量以高亮显示,e代表空字符串)。

符号 替换规则
\ (\:)?
(\\)?
\(\\)*
(\\)?
\ H\ V
\
\ [\(\)?]
\ e\ -\- -
\ \ \
\ \ \
\ (\(,\)*)
\ (\)?(\)(@\)?
\ ==\ <=\ >=
\ \ \ (see note)
\ \ \
\ \ \
\ 作为C符号解析。必须是视图字典中的一个key,对应一个NSView对象。
\ 作为C符号解析。必须是数量字典中的一个key,对应一个NSNumber对象。
\ 根据C语言本地化配置,使用strtod_l解析(将ASCII字符串转化为浮点数)。

注意

对于objectOfPredicate来说,如果条件同视图宽高相关,则接受viewName作为参数。也就是说,可以通过[view1(==view2)]的形式规定view1view2等宽。

如果出现句法错误,则程序抛出异常,同时输出诊断信息。例如:

  1. Expected ':' after 'V' to specify vertical arrangement
  2. V|[backgroundBox]|
  3. ^
  4. A predicate on a view's thickness must end with ')' and the view must end with ']'
  5. |[whiteBox1][blackBox4(blackWidth][redBox]|
  6. ^
  7. Unable to find view with name blackBox
  8. |[whiteBox2][blackBox]
  9. ^
  10. Unknown relation. Must be ==, >=, or <=
  11. V:|[blackBox4(>30)]|
  12. ^