本文主要介绍Masonry更新约束:mas_updateConstraints,核心代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.scale = 1;
// 创建 red view
UIButton *redButton = [[UIButton alloc] init];
redButton.backgroundColor = [UIColor redColor];
[self.view addSubview:redButton];
self.redButton = redButton;
[self.redButton addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
// 可以给red button更新初始约束
// [self.redButton mas_updateConstraints:^(MASConstraintMaker *make) {
//
// // 约束中点位置为父控件的中点位置
// make.center.equalTo(self.view);
// // 约束宽高初始值为200,并且优先级最低
// make.width.height.equalTo(@(200 * self.scale)).priorityLow();
//
// // 约束宽高小于等于父控件的宽高
// make.width.height.lessThanOrEqualTo(self.view);
//
// }];
// 也直接更新视图约束,调用updateViewConstraints方法
[self.view updateConstraintsIfNeeded];
}
- (void)updateViewConstraints {
[super updateViewConstraints];
// 更新约束
[self.redButton mas_updateConstraints:^(MASConstraintMaker *make) {
// 约束中点位置为父控件的中点位置
make.center.equalTo(self.view);
// 约束宽高初始值为200,并且优先级最低
make.width.height.equalTo(@(200 * self.scale)).priorityLow();
// 约束宽高小于等于父控件的宽高
make.width.height.lessThanOrEqualTo(self.view);
}];
}
- (void)click {
self.scale += 0.25;
// 询问self.view是否需要更新
[self.view setNeedsUpdateConstraints];
// 如果需要更新就更新
[self.view updateConstraintsIfNeeded];
// 开始动画更新
[UIView animateWithDuration:1.0 animations:^{
[self.view layoutIfNeeded];
}];
}
当一个控件的约束已经确定,那么如何来更新它的约束呢,而更新约束还可以设置动画。首先:
// 约束中点位置为父控件的中点位置
make.center.equalTo(self.view);
// 约束宽高初始值为200,并且优先级最低
make.width.height.equalTo(@(200 * self.scale)).priorityLow();
// 约束宽高小于等于父控件的宽高
make.width.height.lessThanOrEqualTo(self.view);
意思:使控件与父视图始终保持居中,控件的宽和高最大不能超过屏幕,且控件的宽和高可以变化。由于我们设置了第二行的代码优先级为
priorityLow
,因此其优先级是最低的,所以就可以保证宽高不能超过屏幕。
当点击按钮的时候,调用下面方法
// 询问self.view是否需要更新
[self.view setNeedsUpdateConstraints];
// 如果需要更新就更新
[self.view updateConstraintsIfNeeded];
// 开始动画更新
[UIView animateWithDuration:1.0 animations:^{
[self.view layoutIfNeeded];
}];
询问self.view是否更新约束,如果更新就更新,然后就看是执行更新的约束。其中最关键的代码就是updateConstraintsIfNeed。动画之所以能执行就是靠最后一句代码layoutIfNeeded。
这三句代码的实质就是调用updateViewContraints方法。