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

Masonry 自動布局筆記:用優雅鏈式語法馴服 AutoLayout

編輯:iOS 開發綜合

一、Masonry 是什麼

我們先前在螢幕適配的章節學過 AutoLayout,但那都是在可視化界面上拉出約束的。實務中,我們往往需要直接在程式碼裡撰寫 AutoLayout 約束。Apple 雖然提供了 NSLayoutConstraint 類別來表示約束,但原生寫法相當繁瑣、程式碼量龐大。光是建立一條約束的方法就長這樣:

+ (id)constraintWithItem:(id)view1 /* 一個 UIView */ attribute:(NSLayoutAttribute)attribute1 /* 屬性 */ relatedBy:(NSLayoutRelation)relation /* 關系 */ toItem:(id)view2 /* 另一個 UIView */ attribute:(NSLayoutAttribute)attribute2 /* 屬性 */ multiplier:(CGFloat)multiplier /* 倍數 */ constant:(CGFloat)constant; /* 偏移 */

約束一多,這個方法的呼叫次數就直線上升,程式碼瞬間變得又臭又長。此時不妨借助第三方框架 Masonry——它是一個輕量級的布局框架,把 AutoLayout 封裝起來,並提供自有的描述語法,採用更優雅的鏈式寫法,簡潔明瞭、可讀性極高。

Masonry 幾乎支援 AutoLayout 的所有屬性:

@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;

這些屬性與 NSLayoutAttribute 的對照關係如下圖:

二、Masonry 的使用

Masonry 為 UIView 實作了大量分類(category),讓我們能輕鬆地為視圖添加約束。以下是三個核心的添加約束方法:

/* 添加新約束,只負責新增約束,不能同時存在兩條針對於同一對象的約束,否則會報錯 */ -(NSArray*)mas_makeConstraints:(void(^)(MASConstraintMaker*make))block; /* 更新原有的約束,會更新在 block 中出現的約束,不會導致出現兩個相同約束的情況 */ -(NSArray*)mas_updateConstraints:(void(^)(MASConstraintMaker*make))block; /* 刪除之前約束,重新添加約束,會清除之前的所有約束,僅保留最新的約束 */ -(NSArray*)mas_remakeConstraints:(void(^)(MASConstraintMaker*make))block;

這三個方法不僅 UIView 能呼叫,存放 UIView 的 NSArray 陣列也能呼叫,表示會遍歷陣列中的所有 UIView 逐一套用。

下面是 Block 中常用的約束語法([attribute] 表示屬性,[value] 表示值):

/* 屬性 attribute 可以連用,比如 top.right.bottom.left,加 mas_ 前綴和沒加效果差不多,只是加 mas_ 前綴會對參數裝箱,參數有結構體時需要使用 mas_ 前綴,沒加前綴的參數必須為對象 */ /* 數值約束,top 對應 NSInteger,center 對應 NSPoint,size 對應 NSSize */ make.[attribute].mas_equalTo([value]); /* 等於約束,兩個 view 之間比較,edges 對應 otherView */ make.[attribute].equalTo(otherView.[attribute]); /* 大於等於約束 */ make.[attribute].greaterThanOrEqualTo(otherView.[attribute]); /* 小於等於約束 */ make.[attribute].lessThanOrEqualTo(otherView.[attribute]); /* 偏移約束 */ make.[attribute].equalTo(otherView.[attribute]).offset([value]); /* 邊界約束,有上、下、左、右邊界 */ make.edges.equalTo(otherView).insets(UIEdgeInsetsMake([topValue],[leftValue],[bottomValue],[rightValue])); /* Margin 約束 */ make.[attribute].equalTo(otherView.[attribute]Margin);
注意:

添加約束前,必須先把 UIView 加到父視圖中,否則程式會閃退。

實例一(基礎):居中顯示一個 view

- (void)viewDidLoad { [super viewDidLoad]; UIView *sv = [[UIView alloc] init]; sv.backgroundColor = [UIColor blackColor]; //一定要先將 view 添加到 superView 上,否則會出錯 [self.view addSubview:sv]; __weak ViewController *weakSelf = self; [sv mas_makeConstraints:^(MASConstraintMaker *make) { make.center.equalTo(weakSelf.view);//將 sv 居中 make.size.mas_equalTo(CGSizeMake(300,300));//將 sv 的尺寸設置為 (300,300) }]; }

實例二(初級):讓一個 view 略小於 superView(邊距為 10)

UIView *sv = [[UIView alloc] init]; sv.backgroundColor = [UIColor blackColor]; [self.view addSubview:sv]; __weak ViewController *weakSelf = self; [sv mas_makeConstraints:^(MASConstraintMaker *make) { make.center.equalTo(weakSelf.view); make.size.mas_equalTo(CGSizeMake(300,300)); }]; UIView *sv1 = [[UIView alloc] init]; sv1.backgroundColor = [UIColor redColor]; [sv addSubview:sv1]; [sv1 mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(sv).with.insets(UIEdgeInsetsMake(10, 10, 10, 10)); /*等價於 make.top.equalTo(sv).with.offset(10); make.left.equalTo(sv).with.offset(10); make.bottom.equalTo(sv).with.offset(-10); make.right.equalTo(sv).with.offset(-10); */ }];

值得一提的是,with 和 and 這兩個方法其實什麼事都沒做,只是讓鏈式語法讀起來更順:

-(MASConstraint*)with{ return self; } -(MASConstraint*)and{ return self; }

實例三(初級):兩個高度為 150 的 view 垂直居中、等寬、等間隔排列(間隔為 10)

透過讓左右兩個 view 互相參照對方的邊界,並把寬度設為相等,就能自動算出各自的寬度:

int padding1 = 10; UIView *leftView = [[UIView alloc] init]; leftView.backgroundColor = [UIColor orangeColor]; [sv addSubview:leftView]; UIView *rightView = [[UIView alloc] init]; rightView.backgroundColor = [UIColor orangeColor]; [sv addSubview:rightView]; [leftView mas_makeConstraints:^(MASConstraintMaker*make){ make.centerY.mas_equalTo(sv.mas_centerY); make.left.equalTo(sv.mas_left).with.offset(padding1); make.right.equalTo(rightView.mas_left).with.offset(-padding1); make.height.mas_equalTo(@150); make.width.equalTo(rightView); }]; [rightView mas_makeConstraints:^(MASConstraintMaker*make){ make.centerY.mas_equalTo(sv.mas_centerY); make.left.equalTo(leftView.mas_right).with.offset(padding1); make.right.equalTo(sv.mas_right).with.offset(-padding1); make.height.mas_equalTo(@150); make.width.equalTo(leftView); }];

實例四(中級):在 UIScrollView 中排序一些 view 並自動計算 contentSize

關鍵技巧是:在 ScrollView 內部放一個容器 view,讓容器左右緊貼 ScrollView、寬度與其相等,再把子 view 依序堆疊,最後讓容器底部與最後一個子 view 的底部對齊,contentSize 便會自動撐開:

UIScrollView *scrollView = [[UIScrollView alloc] init]; scrollView.backgroundColor = [UIColor whiteColor]; [sv addSubview:scrollView]; [scrollView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(sv).with.insets(UIEdgeInsetsMake(5,5,5,5)); }]; UIView *container = [[UIView alloc] init]; [scrollView addSubview:container]; [container mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(scrollView); make.width.equalTo(scrollView); }]; int count = 10; UIView *lastView = nil; for(int i = 1;i <= count;++i ){ UIView *subView = [[UIView alloc] init]; [container addSubview:subView]; subView.backgroundColor = [UIColor colorWithRed:( arc4random() % 256 / 256.0 ) green:( arc4random() % 256 / 256.0 ) blue:( arc4random() % 256 / 256.0 ) alpha:1]; [subView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.and.right.equalTo(container); make.height.mas_equalTo(@(20*i)); if ( lastView ) { make.top.mas_equalTo(lastView.mas_bottom); } else { make.top.mas_equalTo(container.mas_top); } }]; lastView = subView; } [container mas_makeConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(lastView.mas_bottom); }];

三、Masonry 進階

Masonry 為 NSArray 實作了兩個特殊的等間距分類方法,讓多個 view 的排列更加省事:

/* 水平等寬定距,或垂直等高定距約束。先確定間距,寬度或高度相等但不確定 axisType 只有 MASAxisTypeHorizontal(水平)和 MASAxisTypeVertical(垂直) fixedSpacing 是 UIView 兩兩之間的間距 leadSpacing 是第一個 UIView 距離 superView 左(或上)邊界的間距 tailSpacing 是最後一個 UIView 距離 superView 右(或下)邊界的間距 */ - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; /* 水平定寬等距,或垂直定高等距約束。先確定寬度或高度,間距相等但不確定 */ - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;

使用範例如下:

/* 水平等寬定距:view 之間水平間距 20,第一個距左邊 6,最後一個距右邊 7,高度 60,距頂部 40 */ [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:6 tailSpacing:7]; [array mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(@40); make.height.equalTo(@60); }];
/* 水平定寬等距:所有 view 寬度 20,第一個距左邊 6,最後一個距右邊 7,高度 60,距頂部 40 */ [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:20 leadSpacing:6 tailSpacing:7]; [array mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(@40); make.height.equalTo(@60); }];
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved