我們知道做開發都需要屏幕適配,做屏幕適配就少不了界面UI的自動布局。那么自動布局的方式常用有哪些呢?在storyboard/xib上我們可以使用Autolayout和Autoresizing,這兩個技術使用起來是很方便的。但是如果我們用代碼來添加子控價,需要對子控件做自動布局呢?放心,有的是方法。第一,可以用蘋果自帶的自動布局類NSLayoutConstraint來做自動布局。第二,可以選擇使用蘋果為了簡化Autolayout的編碼而推出的抽象語言--VFL。第三,使用第三方框架,也就是Masonry。做過開發的朋友都知道使用第一,第二種方式是很蛋疼的,開發效率低而且非常繁瑣。所以接下來就給大家介紹第三方框架Masonry的基本使用。
```
//約束放在block內就可
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
//這句是萬能公式理解這句之后這個框架也就理解了。
//make就是以上的redView,以下這句話的意思是redView的頂部等于父控件的頂部乘以1.0再加上20
make.top.equalTo(self.view.mas_top).multipliedBy(1.0).offset(20);
make.left.equalTo(self.view.mas_left).offset(20);
make.right.equalTo(self.view.mas_right).offset(-20);
make.bottom.equalTo(self.view.mas_bottom).offset(-20);
}];
```
```
//還有簡單的寫法
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
//默認就是乘以1.0,如果沒什么特殊要求的話可以省略multipliedBy
make.top.equalTo(self.view).offset(20);
make.left.equalTo(self.view).offset(20);
make.right.equalTo(self.view).offset(-20);
make.bottom.equalTo(self.view).offset(-20);
}];
```
```
//可以省略父控件
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(20);
make.left.offset(20);
make.right.offset(-20);
make.bottom.offset(-20);
}];
```
```
//甚至可以合起來寫
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.and.left.offset(20);
make.right.and.bottom.offset(-20);
}];
//and是英文語法,完全可以省略
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.offset(20);
make.right.bottom.offset(-20);
}];
```
寫到這里大家應該知道Masonry的使用時那么靈活多變了吧。但是僅僅這樣并不能完全掌握Masonry,因為它還有一些注意點和技巧。
//在導入頭文件之前添加這兩個宏可以省略框架的前綴mas_
//可以省略參數的mas_
#define MAS_SHORTHAND
//可以省略equalTo的mas_
#define MAS_SHORTHAND_GLOBALS
/*
mas_equalTo:可以接收基本數據類型和對象
equalTo:只能接收對象類型
但是用宏省略了以后就可以接收基本數據類型
*/
// 更新約束:如果之前有這個約束,會直接更新;如果沒有會添加新的約束
[blueView updateConstraints:^(MASConstraintMaker *make) {
}];
// 刪除之前所有的約束,添加新的約束
[blueView remakeConstraints:^(MASConstraintMaker *make) {
}];