Visual Format Language(VFL)是 AutoLayout 提供的一種字串式語法,用一行字就能描述多個視圖之間的約束關係,適合用來處理一排等距排列的元件。以下先列出完整的文法定義,再逐一說明實際寫法。
<visualFormatString> (<orientation>:)?(<superview><connection>)?<view>(<connection><view>)*(<connection><superview>)? <orientation> H | V <superview> | <view> [<viewName>(<predicateListWithParens>)?] <connection> e | -<predicateList>- | - <predicateList> <simplePredicate> | <predicateListWithParens> <simplePredicate> <metricName> | <positiveNumber> <predicateListWithParens> (<predicate>(,<predicate>)*) <predicate> (<relation>)?(<objectOfPredicate>)(@<priority>)? <relation> == | <= | >= <objectOfPredicate> <constant> | <viewName> <priority> <metricName> | <number> <constant> <metricName> | <number>
viewName:解析為 C 識別字,必須是傳入 views 字典中的一個鍵,對應到某個 view 實例。
metricName:同樣解析為 C 識別字,必須是傳入 metrics 字典中的鍵,對應到某個 NSNumber 實例。
number:以 C locale 透過 strtod_l 解析。
以 btn1 與 btn2 為例:
[btn1]-[btn2] // 標準連接符號「-」代表相距標準距離(約 8pt)
[btn1(>=10)] // btn1 寬度至少為 10
H:|-50-[btn1]-30-| // H 代表水平方向,"|" 代表父視圖
// 表示 btn1 距父視圖左邊 50、右邊 30
[btn1(==btn2)] // btn1 與 btn2 寬度相等
[btn1(>=10,<=50)] // btn1 寬度介於 10 到 50 之間
最簡單的形式可以寫成:
|-|[btn1]-|
也可以帶上固定間距:
|-50-[btn1]-|
或者把間距寫成區間條件:
|-(>=10,<=30)-[btn1(>=30)]-(<=20)-|
VFL 的優勢在於簡潔,一行字串就能取代大量 NSLayoutConstraint 的建立程式碼;缺點是可讀性與除錯難度較高,寫錯時編譯器不會給你友善的提示。實務上常見的做法是:排列等寬等距的元件用 VFL,涉及單一元件的細節約束則用 API 逐條設定。另外要記得,字串中出現的 view 名稱必須與 options 中的 NSLayoutFormatOptions 及 views 字典鍵完全一致,否則會在執行期拋出例外。