前言
說到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
50
51
52
53
54
55
56
57
58
59
|
@interface RemakeContraintsController ()
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) BOOL isExpanded;
@end
@implementation RemakeContraintsController
- (void)viewDidLoad {
[super viewDidLoad];
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.growingButton setTitle:@"點我展開" forState:UIControlStateNormal];
self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;
self.growingButton.layer.borderWidth = 3;
self.growingButton.backgroundColor = [UIColor redColor];
[self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.growingButton];
self.isExpanded = NO;
}
- (void)updateViewConstraints {
// 這里使用update也是一樣的。
// remake會將之前的全部移除,然后重新添加
[self.growingButton mas_remakeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(0);
make.left.right.mas_equalTo(0);
if (self.isExpanded) {
make.bottom.mas_equalTo(0);
} else {
make.bottom.mas_equalTo(-350);
}
}];
[super updateViewConstraints];
}
- (void)onGrowButtonTaped:(UIButton *)sender {
self.isExpanded = !self.isExpanded;
if (!self.isExpanded) {
[self.growingButton setTitle:@"點我展開" forState:UIControlStateNormal];
} else {
[self.growingButton setTitle:@"點我收起" forState:UIControlStateNormal];
}
// 告訴self.view約束需要更新
[self.view setNeedsUpdateConstraints];
// 調用此方法告訴self.view檢測是否需要更新約束,若需要則更新,下面添加動畫效果才起作用
[self.view updateConstraintsIfNeeded];
[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
}];
}
@end
|
講解
移除之前的所有約束,然后添加新約束的方法是:mas_remakeConstraints。
這里展開與收起的關鍵代碼在這里:
|
1
2
3
4
5
6
7
|
if (self.isExpanded) {
make.bottom.mas_equalTo(0);
} else {
make.bottom.mas_equalTo(-350);
}
|
想要更新約束時添加動畫,就需要調用關鍵的一行代碼:setNeedsUpdateConstraints,這是選擇對應的視圖中的約束需要更新。
對於updateConstraintsIfNeeded這個方法並不是必須的,但是有時候不調用就無法起到我們的效果。但是,官方都是這么寫的,從約束的更新原理上講,這應該寫上。我們要使約束立即生效,就必須調用layoutIfNeeded此方法。看下面的方法,就是動畫更新約束的核心代碼:
|
1
2
3
4
5
6
7
8
9
10
|
// 告訴self.view約束需要更新
[self.view setNeedsUpdateConstraints];
// 調用此方法告訴self.view檢測是否需要更新約束,若需要則更新,下面添加動畫效果才起作用
[self.view updateConstraintsIfNeeded];
[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
}];
|
