您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

NSLayoutConstraint 入門:看懂 Auto Layout 約束的那條方程式

編輯:iOS 開發綜合

Auto Layout 看起來抽象,其實整個體系都建立在一條線性方程式上。理解這條式子,之後不管是寫程式碼加約束還是 debug 約束衝突,都會輕鬆許多。

動手之前,兩個必要設定

  1. 以程式碼建立約束時,要先把 translatesAutoresizingMaskIntoConstraints 設為 NO,否則系統會自動產生一組 autoresizing mask 約束與你的約束打架。
  2. 更新約束的位置有講究:ViewController 請寫在 -updateViewConstraints 中;View 則寫在 -updateConstraints 中。

核心方法與那條方程式

/* Create constraints explicitly.
   Constraints are of the form "view1.attr1 = view2.attr2 * multiplier + constant"
   If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute. */
+ (instancetype)constraintWithItem:(id)view1
                         attribute:(NSLayoutAttribute)attr1
                         relatedBy:(NSLayoutRelation)relation
                            toItem:(id)view2
                         attribute:(NSLayoutAttribute)attr2
                        multiplier:(CGFloat)multiplier
                          constant:(CGFloat)c;

七個參數可以這樣讀:

  • view1 / attr1:被約束的視圖,以及要約束它的哪個屬性。
  • relation:兩個屬性之間的關係(等於、小於等於、大於等於)。
  • view2 / attr2:參照物件與參照屬性;若沒有參照物件,就傳 nil 與 NSLayoutAttributeNotAnAttribute。
  • multiplier:attr1 是 attr2 的幾倍。
  • c:最後要加上的常數偏移。

合起來就是:view1.attr1 [= / <= / >=] view2.attr2 * multiplier + c

NSLayoutAttribute 分三組來記

常用幾何屬性

NSLayoutAttributeLeft      // CGRectGetMinX(view.frame)
NSLayoutAttributeRight     // CGRectGetMaxX(view.frame)
NSLayoutAttributeTop       // CGRectGetMinY(view.frame)
NSLayoutAttributeBottom    // CGRectGetMaxY(view.frame)
NSLayoutAttributeWidth     // CGRectGetWidth(view.frame)
NSLayoutAttributeHeight    // CGRectGetHeight(view.frame)
NSLayoutAttributeCenterX   // view.center.x
NSLayoutAttributeCenterY   // view.center.y

另有文字基線相關的 NSLayoutAttributeBaseline(多數視圖等同 Bottom,但在 UILabel 上指的是字母底部實際落點)、FirstBaseline(iOS 8 起)與 LastBaseline,以及代表「不指定屬性」的 NSLayoutAttributeNotAnAttribute。

伴隨語系方向的 Leading / Trailing

在由左至右閱讀的地區,Leading 等同 Left、Trailing 等同 Right;在由右至左閱讀的地區則相反。要支援阿拉伯語、希伯來語等 RTL 語系時,用這兩個屬性才能自動鏡像。

iOS 8 新增的邊距屬性

LeftMargin、RightMargin、TopMargin、BottomMargin、LeadingMargin、TrailingMargin、CenterXWithinMargins、CenterYWithinMargins 這八個屬性會參照視圖的 layoutMargins,讓間距跟隨系統建議值,不必寫死數字。

NSLayoutRelation:三種運算子

NSLayoutRelationLessThanOrEqual    // <=
NSLayoutRelationEqual              // =
NSLayoutRelationGreaterThanOrEqual // >=

約束的安裝與移除

讀取當前視圖上的所有約束用 -constraints。舊版的 addConstraint:、addConstraints:、removeConstraint:、removeConstraints: 已被標記為即將淘汰,蘋果建議改用 iOS 8 提供的 active 屬性或 +activateConstraints:/+deactivateConstraints:。批次啟停不僅語意清楚,效能通常也更好。

@property (getter=isActive) BOOL active;    // 只有 active 的約束才參與計算

+ (void)activateConstraints:(NSArray *)constraints;
+ (void)deactivateConstraints:(NSArray *)constraints;

實際寫寫看

把 view1 做成 20×20 的方形

寫法一,寬高各自固定:

[self addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20]];

寫法二,寬度固定、高度等於寬度:

[self addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:view1 attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];

寫法二的優勢很明顯:要改尺寸時只需要動一個常數,比例永遠不會跑掉。

讓 view1 的左邊與 view2 的左邊對齊

NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:view1
                                                                 attribute:NSLayoutAttributeLeft
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:view2
                                                                 attribute:NSLayoutAttributeLeft
                                                                multiplier:1.0
                                                                  constant:0];
// 舊寫法:[self addConstraint:leftConstraint];
// 新寫法一:[NSLayoutConstraint activateConstraints:@[leftConstraint]];
// 新寫法二:leftConstraint.active = YES;

把這些規則記熟之後,再複雜的版面也不過是幾條方程式的組合而已。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved