說到iOS
自動佈局,有很多的解決辦法。有的人使用xib/storyboard
自動佈局,也有人使用frame
來適配。對於前者,筆者並不喜歡,也不支持。對於後者,更是麻煩,到處計算高度、寬度等,千萬大量代碼的冗餘,對維護和開發的效率都很低。
筆者在這裏介紹純代碼自動佈局的第三方庫:Masonry
。這個庫使用率相當高,在全世界都有大量的開發者在使用,其star
數量也是相當高的。
效果圖
本節詳解Masonry
的基本用法,先看看效果圖:
我們這裏要佈局使這三個控件的高度一致,而綠色和紅色的控件高度和寬度相待。
核心代碼
看下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
-
(void)viewDidLoad
{
[super
viewDidLoad];
UIView
*greenView
=
UIView.new;
greenView.backgroundColor
=
UIColor.greenColor;
greenView.layer.borderColor
=
UIColor.blackColor.CGColor;
greenView.layer.borderWidth
=
2;
[self.view
addSubview:greenView];
UIView
*redView
=
UIView.new;
redView.backgroundColor
=
UIColor.redColor;
redView.layer.borderColor
=
UIColor.blackColor.CGColor;
redView.layer.borderWidth
=
2;
[self.view
addSubview:redView];
UIView
*blueView
=
UIView.new;
blueView.backgroundColor
=
UIColor.blueColor;
blueView.layer.borderColor
=
UIColor.blackColor.CGColor;
blueView.layer.borderWidth
=
2;
[self.view
addSubview:blueView];
//
使這三個控件等高
CGFloat
padding
=
10;
[greenView
mas_makeConstraints:^(MASConstraintMaker
*make)
{
make.top.mas_equalTo(padding);
make.left.mas_equalTo(padding);
make.right.mas_equalTo(redView.mas_left).offset(-padding);
make.bottom.mas_equalTo(blueView.mas_top).offset(-padding);
//
三個控件等高
make.height.mas_equalTo(@[redView,
blueView]);
//
紅、綠這兩個控件等高
make.width.mas_equalTo(redView);
}];
[redView
mas_makeConstraints:^(MASConstraintMaker
*make)
{
make.top.height.bottom.mas_equalTo(greenView);
make.right.mas_equalTo(-padding);
make.left.mas_equalTo(greenView.mas_right).offset(padding);
}];
[blueView
mas_makeConstraints:^(MASConstraintMaker
*make)
{
make.height.mas_equalTo(greenView);
make.bottom.mas_equalTo(-padding);
make.left.mas_equalTo(padding);
make.right.mas_equalTo(-padding);
}];
}
|
講解
添加約束的方法是:mas_makeConstraints
。我們可以看到,約束可以使用鏈式方式,使用方法很簡單,看起來像一句話。
看這句話:make.top.height.bottom.mas_equalTo(greenView)
,意思是:使我的頂部、高度和底部都與greenView
的頂部、高度和底部相等。因此,只要greenView
的約束添加好了,那麼redView
的頂部、高度和底部也就自動計算出來了。
大多時候,我們並不會將一句話完整地寫出來,而是使用簡寫的方式。如:
1
2
3
|
make.right.mas_equalTo(-padding);
|
其完整寫法爲:
1
2
3
|
make.right.mas_equalTo(bludView.superView.mas_right).offset(-padding);
|
當我們是要與父控件相對約束時,可以省略掉父視圖。注意,並不是什麼時候都可以省略,只有約束是同樣的纔可以省略。比如,約束都是right
纔可以。如果是一個left
一個是right
,那麼就不能省略了。
源代碼
大家可以到筆者的github
下載源代碼:https://github.com/CoderJackyHuang/MasonryDemo
溫馨提示:本節所講內容對應於
BasicController
中的內容
關注我
微信公衆號:iOSDevShares
有問必答QQ羣:324400294