iOS 8 之後,不少開發者為了螢幕適配傷透腦筋,AutoLayout 也因此被廣泛討論。但它的價值遠不只「適配多尺寸」——它真正給開發者的是一套全新的佈局思維。
本文依據實際專案經驗,分三個方向完整說明:一、佈局原理與語法;二、約束衝突與動畫處理;三、佈局思維與約束鏈控制。內容與程式碼主要依賴名為 UIView+AutoLayout 的分類,文末會附上專案資訊。
學 AutoLayout 之前,必須先徹底放下 frame 思維,思想扭轉過來之後學習效率會高很多。
AutoLayout 是 iOS 6 引入的機制。傳統做法中,每個 view 都有 frame 屬性,它其實是個結構體:
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CGRect CGRect;
一個管座標,一個管大小。而 AutoLayout 是靠「約束」來決定佈局的——一旦 view 改用約束,它的 frame 將永遠是 0,你無法再從 frame 得知它真實的位置與尺寸。
因此動手前有兩件準備工作:
1. 把 translatesAutoresizingMaskIntoConstraints 設為 NO。
2. 若使用 AutoLayout 的是 viewController,適配程式碼寫在 - (void)updateViewConstraints 中;若是 view,則寫在 - (void)updateConstraints 中。這其實正是 AutoLayout 的優點之一:能把一個 controller 或 view 的所有適配集中在一個方法裡。
任何 AutoLayout 語法,最終都是建立一個 NSLayoutConstraint 物件並加入 view 的約束集合。官方 API 給出的計算形式為:
view1.attr1 = view2.attr2 * multiplier + constant
建立一個約束需要七個參數:
(1)WithItem:被約束物件
(2)第一個 attribute:被約束物件的屬性
(3)relatedBy:約束的比較關係
(4)toItem:約束來源物件
(5)第二個 attribute:約束來源的屬性
(6)multiplier:約束係數
(7)constant:約束常數
第一組屬性枚舉定義了可被約束的對象:
typedef NS_ENUM(NSInteger, NSLayoutAttribute) {
NSLayoutAttributeLeft = 1,
NSLayoutAttributeRight,
NSLayoutAttributeTop,
NSLayoutAttributeBottom,
NSLayoutAttributeLeading,
NSLayoutAttributeTrailing,
NSLayoutAttributeWidth,
NSLayoutAttributeHeight,
NSLayoutAttributeCenterX,
NSLayoutAttributeCenterY,
NSLayoutAttributeBaseline,
NSLayoutAttributeLastBaseline = NSLayoutAttributeBaseline,
NSLayoutAttributeFirstBaseline NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeLeftMargin NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeRightMargin NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeTopMargin NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeBottomMargin NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeLeadingMargin NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeTrailingMargin NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeCenterXWithinMargins NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeCenterYWithinMargins NS_ENUM_AVAILABLE_IOS(8_0),
NSLayoutAttributeNotAnAttribute = 0
};
其中 Leading 與 Trailing 實際上等於 left 與 right,差別在於它們會依語言書寫方向自動對調(阿拉伯語等由右至左的語言用得上)。可以看到,約束對象不外乎上下左右、寬、高、中心橫座標與中心縱座標。
第二組是比較關係:
typedef NS_ENUM(NSInteger, NSLayoutRelation) {
NSLayoutRelationLessThanOrEqual = -1,
NSLayoutRelationEqual = 0,
NSLayoutRelationGreaterThanOrEqual = 1
};
也就是 <=、==、>=。AutoLayout 的靈活與動態性主要就來自這組關係——當尺寸或座標無法確定時,用不等式描述上下限,比寫死數值強得多。係數與常數則參與最終計算,同樣遵循上面那條公式。
[View autoSetDimension:ALDimensionWidth toSize:30];
底層等價寫法:
NSLayoutConstraint *constraint =
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0.0f
constant:size];
[View addConstraint:constraint];
因為只約束自身尺寸,不需要約束來源,toItem 傳 nil,第二個 attribute 自然是 NSLayoutAttributeNotAnAttribute。依此類推,理論上也能把兩個 view 的寬度綁在一起,但實務上很少這麼做,原因後面會談。
[View1 autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:View1 withOffset:5];
底層等價寫法:
NSLayoutConstraint *constraint =
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:View2
attribute:NSLayoutAttributeLeft
multiplier:1.0f
constant:5];
[View1 addConstraint:constraint];
意思是 view1 的最左邊到 view2 的最左邊距離為 5(係數為 1)。
[view1 autoAlignAxisToSuperviewAxis:ALAxisVertical];
底層等價寫法:
NSLayoutConstraint *constraint =
[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:view1.superview
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f];
也就是讓 view1 的水平中心與父 view 的水平中心對齊。
既然所有語法背後都是同一個 NSLayoutConstraint,代碼自然大同小異。以下說明 UIView+AutoLayout 的分類用法,其方法大致也分成三類。

typedef NS_ENUM(NSInteger, ALDimension) {
ALDimensionWidth = NSLayoutAttributeWidth, // view 的寬
ALDimensionHeight = NSLayoutAttributeHeight // view 的高
};

typedef NS_ENUM(NSInteger, ALEdge) {
ALEdgeLeft = NSLayoutAttributeLeft, // 左邊
ALEdgeRight = NSLayoutAttributeRight, // 右邊
ALEdgeTop = NSLayoutAttributeTop, // 上邊
ALEdgeBottom = NSLayoutAttributeBottom, // 下邊
ALEdgeLeading = NSLayoutAttributeLeading, // 依語言方向決定的起始邊
ALEdgeTrailing = NSLayoutAttributeTrailing // 依語言方向決定的結束邊
};

typedef NS_ENUM(NSInteger, ALAxis) {
ALAxisVertical = NSLayoutAttributeCenterX, // 通過中心的垂直線
ALAxisHorizontal = NSLayoutAttributeCenterY, // 通過中心的水平線
ALAxisBaseline = NSLayoutAttributeBaseline // 文字基線(並非所有 view 適用)
};
第一節小結:AutoLayout 底層只有一個 NSLayoutConstraint,UIView+AutoLayout 做的事就是把七個參數包裝成更直觀的介面。

這個頁面完全由 AutoLayout 佈局,結構是:頂部 label1 與右上 button1,中間 imageview1 與 label2,下方兩個自訂 cellView1、cellView2,再下面 button2(最底部的小提示不計)。cellView1、cellView2 內部還有各自的 image view 與 label。
重點規則:當父 view1 有子 view2,而 view2 又有子 view3 時,約束 view3 會同時對它的父 view 產生影響——只要那個父 view 不是最上層。這條規則確實容易讓人困惑,遇到衝突時只能靠實際案例慢慢摸清。
如果 view 已改用約束佈局,frame 恆為 0,傳統「改 frame 做平移」的方式自然失效。以下由難到易列出三種方案:
1. 呼叫 [self.view layoutIfNeeded] 搭配改動約束常數,再包在 animation block 中。這是最正統的做法,但對初學者門檻最高。
2. 改動 view 的 bounds 屬性。在 AutoLayout 環境下 bounds 仍然有效,改寫起來相對直觀。
3. 改動 transform 屬性。例如要向上平移 10pt:
self.transform = CGAffineTransformMakeTranslation(0, -10);
這是最簡單也最好處理的方式,缺點是它屬於「視覺位移」,並未改變 view 在佈局系統中的實際位置,後續若有依賴 frame 的計算需特別留意。

接著用同一個頁面說明。要佈局 cellView1 最左邊那個「招商銀行」logo 的 imageview,直覺寫法是把上下左右四條邊都約束一遍:
[imageview autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self withOffset:5]; [imageview autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self withOffset:5]; [imageview autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self withOffset:5]; [imageview autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:self withOffset:35];
四行分別表示:頂部距父 view 頂部 5、底部距父 view 底部 5、左側距父 view 左側 5、右側距父 view 左側 35。若父 view 高 40,imageview 的尺寸會被推導成 (30, 30),看似沒問題。
但這其實已經過度約束了。當父 view 高度變成 50,imageview 會因頂底約束被算成 (30, 40),方形圖片就變形了。這並不是 AutoLayout 想表達的意思。
換一種寫法:
[ImageView autoSetDimensionsToSize:CGSizeMake(30, 30)]; [ImageView autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self withOffset:5]; [ImageView autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
三行分別約束:固定尺寸 (30, 30)、左側距父 view 左側 5、垂直中心與父 view 對齊。這樣一來,無論父 view 怎麼改變大小與位置,image 自身的形狀與相對位置都穩定不變。
AutoLayout 真正的語法只有一個方法,理解那七個參數的含義,原理就不難掌握。所以對開發者而言,重點不在於程式碼寫起來有多冗長——畢竟有不少三方庫能幫你簡化;真正要掌握的是這種佈局思維:心中要有一條約束鏈,用最少的約束精準描述「這個 view 相對於誰、在哪、多大」。約束寫得越克制,佈局就越準確、越容易適配。
我自己也是剛接觸 AutoLayout 不久,以上算是學習心得。仍舊推薦使用 UIView+AutoLayout 這個庫,因為它的封裝夠直觀又貼近底層,對理解原理與掌握內涵反而更有幫助。