Swift. Auto Layout (6)

讓我們認識一下可視化語言(Visual Format Language)的語法吧!

Jeremy Xue
Jeremy Xue ‘s Blog

--

Photo by Siora Photography on Unsplash

▸ 可視化語法

標準間距:

[button]-[textField]

寬度約束:

[button(>=50)]

與 Superview 連結:

|-50-[purpleBox]-50-|

垂直佈局:

V:[topField]-10-[buttonField]

齊平視圖:

[maroonView][blueView]

優先度:

[button(100@20)]

相同寬度:

[button1(==button2)]

多個謂詞(Predicates):

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

完整的佈局線:

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

該符號更喜歡良好的可視化而不是完整的表達性。大多數在真實使用者介面中有用的約束都可以使用可視化語言來表達,但也有一些不能。一個無法表達有用的約束是固定的長寬比(例如:imageView.width = 2 * imageView.height )。要創建這樣的約束,必須使用 constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:

▸ 可視化字串文法:

可視化字符串文法定義如下(其文字以灰色字體所顯示,e 代表空字符)。

NOTE對於 objectOfPredicate 產生式,只有在當謂詞的主體是 View 的高度或寬度時 viewName 才會接受。也就是說,你可以使用 [view1(==view2)] 來指定 view1 與 view2 具有相同的寬度。

如果你犯了一個語法錯誤,則會拋出一個帶有診斷訊息的異常,如以下範例:

Expected ':' after 'V' to specify vertical arrangement
V|[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)]|
^

--

--

Jeremy Xue
Jeremy Xue ‘s Blog

Hi, I’m Jeremy. [好想工作室 — iOS Developer]