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

AutoLayout 第三方庫 Masonry 入門與實踐全解析

編輯:iOS 開發綜合

在當前的 iOS 開發中,AutoLayout 幾乎是必備技能,而且我們是主動擁抱它。最普遍的用法是在 xib 或 storyboard 中可視化地添加約束,這是入門必須掌握的基本功。對於比較簡單的 App,可視化 AutoLayout 或許就夠用了;但一旦 UI 布局稍趨複雜多變,就不得不回到程式碼。偏偏 iOS 原生的代碼自動布局實在過於繁瑣,於是第三方庫 Masonry 應運而生——它入門極為簡單,也是一位稱職 iOS 開發者的必備利器。(本文案例程式碼已上傳至 GitHub。)

安裝:用 CocoaPods 導入

在 Podfile 中加入以下內容即可:

 platform:ios,'8.0' pod 'Masonry'

Masonry 的三種約束方法

Masonry 提供了三個添加約束的核心方法:

- (NSArray *)mas_makeConstraint:(void(^)(MASConstraintMaker *))block;
- (NSArray *)mas_updateConstraint:(void(^)(MASConstraintMaker *))block;
- (NSArray *)mas_remakeConstraint:(void(^)(MASConstraintMaker *))block;

其中,mas_makeConstraint 只負責新增約束,適合初次設置;mas_updateConstraint 更新 block 中出現的約束,若找不到則新增;mas_remakeConstraint 則清除之前所有約束,僅保留最新的約束。

equalTo 與 mas_equalTo 的區別

其實 mas_equalTo 是一個宏,源碼中是這樣定義的:

 #define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__))) #define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__))) #define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__))) #define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__)))

這裡牽涉到兩個簡便寫法,Masonry 提供了不加 mas_ 前綴的方法,只需定義兩個宏:

MAS_SHORTHAND 宏:定義後,就能使用 UIView、NSArray 中不帶 mas_ 前綴的 makeConstraint、updateConstraint、remakeConstraint,以及 UIView 中不帶 mas_ 前綴的 Attribute。

MAS_SHORTHAND_GLOBALS:直接對 equalTo 傳入基礎類型,Masonry 會自動轉化為 NSValue 物件。

比例係數與常數係數

multipliedBy(0.5) 可用來設置比例係數。Masonry 則提供四種設置 Constant 的方法:

 - (MASConstraint * (^)(MASEdgeInsets insets))insets; - (MASConstraint * (^)(CGSize offset))sizeOffset; - (MASConstraint * (^)(CGPoint offset))centerOffset; - (MASConstraint * (^)(CGFloat offset))offset;

其中,insets 方法可同時設置 top、left、bottom、right,接收 MASEdgeInsets(即 UIEdgeInsets)類型,用 UIEdgeInsetsMake 設置;sizeOffset 設置 width、height,接收 CGSize 類型;centerOffset 設置 centerX、centerY;offset 則可設置所有偏移常量。

理解約束的本質

對一條約束而言,它實際表達的是一種相等或不等的關係,例如:

aView.Leading = 1.0 * bView.Trailing + 10;

其中:aView 是 Item1;Leading 是 Attribute1;= 是 Relationship;1.0 是 Multiplier;bView 是 Item2;Trailing 是 Attribute2;10 是 Constant。

MASConstraintMaker 的 22 種 Attribute

 //第一類 @property (nonatomic, strong, readonly) MASConstraint *left; @property (nonatomic, strong, readonly) MASConstraint *top; @property (nonatomic, strong, readonly) MASConstraint *right; @property (nonatomic, strong, readonly) MASConstraint *bottom; @property (nonatomic, strong, readonly) MASConstraint *leading; @property (nonatomic, strong, readonly) MASConstraint *trailing; @property (nonatomic, strong, readonly) MASConstraint *width; @property (nonatomic, strong, readonly) MASConstraint *height; @property (nonatomic, strong, readonly) MASConstraint *centerX; @property (nonatomic, strong, readonly) MASConstraint *centerY; @property (nonatomic, strong, readonly) MASConstraint *baseline; //第二類 @property (nonatomic, strong, readonly) MASConstraint *leftMargin; @property (nonatomic, strong, readonly) MASConstraint *rightMargin; @property (nonatomic, strong, readonly) MASConstraint *topMargin; @property (nonatomic, strong, readonly) MASConstraint *bottomMargin; @property (nonatomic, strong, readonly) MASConstraint *leadingMargin; @property (nonatomic, strong, readonly) MASConstraint *trailingMargin; @property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; @property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins; //第三類 @property (nonatomic, strong, readonly) MASConstraint *edges; @property (nonatomic, strong, readonly) MASConstraint *size; @property (nonatomic, strong, readonly) MASConstraint *center;

第一類是基本屬性,向下支援到 iOS 6,最為常用;第二類是邊緣相關屬性,需 iOS 8 以上,因版本要求較高而用得較少;第三類則是複合屬性——edges 對應 (top,left,right,bottom)、size 對應 (width,height)、center 對應 (centerX,centerY)。

with 的用法與實用技巧

在 Masonry 的鏈式語法中,with 能對一個物件的多個屬性進行連接,但也可以省略。源碼的解釋是:with 是一個可選的語法屬性,沒有任何實際影響,只是能提升約束的可讀性。

幾個實用小技巧:

— 若等式兩邊的 Attribute 相同,可省略右邊的 Attribute;
— 若是等於關係且右邊是父 view,equalTo 也可省略;
— multiplier 默認為 1 時可不寫;
— offset 默認為 0 時可不寫。
所以若不嫌麻煩,為所有約束都補上 multipliedBy() 和 offset(),反而更清楚直觀。

mas_key:讓衝突日誌一目了然

mas_key 相當於 View 原生的 tag,用來區分不同的 View,而且它以字串標識,更為方便直觀。當約束發生衝突、需要印出 Log 時,加上 key 標識後就能輕易定位衝突位置。以下示範。

weakSelf 的必要性

由於 Masonry 的約束寫在 block 中,我們通常會定義一個宏來取得弱參考:

 //定義宏,用於 block #define WeakSelf(weakSelf) __weak __typeof(&*self)weakSelf = self;

在 block 之前先呼叫 WeakSelf(weakSelf);,之後 block 內一律改用 weakSelf,即可避免循環參考。

宏定義的位置

要特別注意,前面提到的兩個宏必須定義在 import 頭文件之前:

 #define MAS_SHORTHAND #define MAS_SHORTHAND_GLOBALS #import "FirstViewController.h" #import "Masonry.h"

動手實踐

【1】繪製一個紅色 View,在螢幕中居中,寬高為 200:

 - (void)setRedView { WeakSelf(weakSelf); self.redView = [[UIView alloc] init]; self.redView.backgroundColor = [UIColor redColor]; //在設置 Autolayout 之前,要將 view 添加到 self.view 上面 [self.view addSubview:self.redView]; [self.redView mas_makeConstraints:^(MASConstraintMaker *make) { make.center.mas_equalTo(weakSelf.view); make.size.mas_equalTo(CGSizeMake(200, 200)); }]; }

請注意:對 redView 設置約束前,一定要先把它加到 self.view 中!

【2】在紅色 View 中繪製一個灰色 View,練習用複合屬性與單一屬性設置四周邊距:

 - (void)setGrayViewEdgeInsetToRedView { WeakSelf(weakSelf); self.grayView = [[UIView alloc] init]; self.grayView.backgroundColor = [UIColor grayColor]; [self.redView addSubview:self.grayView]; [self.grayView mas_makeConstraints:^(MASConstraintMaker *make) { // make.edges.equalTo(weakSelf.redView).with.insets(UIEdgeInsetsMake(20, 20, 20, 20)); make.top.equalTo(weakSelf.redView).offset(20); make.left.equalTo(weakSelf.redView).offset(20); make.bottom.equalTo(weakSelf.redView).offset(-20); make.right.equalTo(weakSelf.redView).offset(-20); }]; }

【3】在灰色 View 內繪製兩個等寬等間距的 View,左右邊距與彼此間距皆為 15,並自動計算寬度:

 - (void)setTwoViewInGrayView { WeakSelf(weakSelf); UIView *subView1 = [[UIView alloc] init]; UIView *subView2 = [[UIView alloc] init]; subView1.backgroundColor = [UIColor orangeColor]; subView2.backgroundColor = [UIColor blueColor]; [self.grayView addSubview:subView1]; [self.grayView addSubview:subView2]; [subView1 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(weakSelf.grayView.mas_centerY); make.left.equalTo(weakSelf.grayView.mas_left).with.offset(15); make.right.equalTo(subView2.mas_left).with.offset(-15); make.height.equalTo(weakSelf.grayView).multipliedBy(0.5); make.width.equalTo(subView2.mas_width); }]; [subView2 mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(weakSelf.grayView.mas_centerY); make.left.equalTo(subView1.mas_right).with.offset(15); make.right.equalTo(weakSelf.grayView.mas_right).offset(-15); make.height.equalTo(weakSelf.grayView).multipliedBy(0.5); make.width.equalTo(subView1.mas_width); }]; }

【4】練習設置比例係數:一個 View 寬度是 self.view 的 0.5 倍再減 10,高度是 self.view 的 0.2 倍,距左邊 10、頂部緊貼紅色 View:

 - (void)setMutiplierAndConstant { WeakSelf(weakSelf); UIView *yellowView = [[UIView alloc] init]; yellowView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:yellowView]; [yellowView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.equalTo(weakSelf.view.mas_width).offset(-10).multipliedBy(0.5); make.height.equalTo(weakSelf.view.mas_height).multipliedBy(0.2).offset(0); make.top.equalTo(weakSelf.redView.mas_bottom).multipliedBy(1).offset(0); make.left.equalTo(weakSelf.view.mas_left).multipliedBy(1).offset(10); }]; }

【5】使用 mas_key,讓約束衝突時的 Log 更清晰。以下是一段帶有衝突的程式碼:

 - (void)setViewWithKey { UIView *firstView = [[UIView alloc] init]; firstView.backgroundColor = [UIColor blackColor]; [self.view addSubview:firstView]; self.view.mas_key = @"self.view"; firstView.mas_key = @"firstView"; [firstView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(100, 100)); make.left.offset(10); make.right.offset(-10); }]; }

若不使用 mas_key 標識,Log 印出的是 View 的記憶體位址,多個 View 時很難閱讀;設定 mas_key 後,Log 會直接顯示 firstView、self.view 等名稱,衝突位置立刻無所遁形。

【6】借助前述兩個宏,使用 Masonry 時可省略 mas_ 前綴,以下程式碼即使去掉前綴也能成功編譯運行:

 - (void)useShorthand { UIView *firstView = [[UIView alloc] init]; firstView.backgroundColor = [UIColor blackColor]; [self.view addSubview:firstView]; self.view.mas_key = @"self.view"; firstView.mas_key = @"firstView"; [firstView makeConstraints:^(MASConstraintMaker *make) { make.size.equalTo(CGSizeMake(100, 100)); make.left.offset(10); make.right.offset(-10); }]; }

以上只是 Masonry 的入門用法,想真正融會貫通,還得在實際項目中反覆磨練;而最佳的學習途徑,莫過於直接研讀 Masonry 的源碼。

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