簡化代碼
// 定義這個(gè)常量弹渔,就可以不用在開發(fā)過程中使用"mas_"前綴舟茶。
#define MAS_SHORTHAND
// 定義這個(gè)常量,就可以讓Masonry幫我們自動(dòng)把基礎(chǔ)數(shù)據(jù)類型的數(shù)據(jù)脐往,自動(dòng)裝箱為對象類型。(即equalTo(此處直接寫數(shù)字))
#define MAS_SHORTHAND_GLOBALS
基本使用
//必須先把加約束的view添加到父視圖上(addsubview)
//然后調(diào)用視圖的 makeConstraints方法進(jìn)行添加視圖
[self.uv makeConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(100*self.scale);
make.width.height.lessThanOrEqualTo(self.view);
make.center.equalTo(self.view);
}];
更新約束
//需要在更新視圖事件函數(shù)調(diào)用的類文件里重寫updateConstranints函數(shù)
- (void)updateViewConstraints{
[self.uv mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(100 * self.scale);
}];
[super updateViewConstraints];
}
//然后在事件函數(shù)中調(diào)用setNeedUpdateConstranints(提交更新約束申請)updateConstranintsIfNeeded(判斷是否需要更新約束 來調(diào)用更新函數(shù))
//最后調(diào)用layoutIfNeeded
//**注意** 更新約束需要在需要更新視圖的父視圖中調(diào)用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.scale ++;
[self.view setNeedsUpdateConstraints];
[self.view updateConstraintsIfNeeded];
[UIView animateWithDuration:1 animations:^{
[self.view layoutIfNeeded];
}];
}
//上面的步驟也可以換成直接調(diào)用updateViewConstraints來寫新的約束來更新
[self.uv updateConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(100 * self.scale);
}];
[UIView animateWithDuration:1 animations:^{
[self.view layoutIfNeeded];
}];
//注意 更新約束是繼承原有約束的 不會(huì)刪除原有約束
重寫約束
mas_remakeConstraints
約束控件高寬比
UIView* uv = [[UIView alloc]init];
uv.backgroundColor = [UIColor purpleColor];
[self.view addSubview:uv];
[uv makeConstraints:^(MASConstraintMaker *make) {
make.top.right.left.equalTo(0);
//注意 相對約束的只能是控件本身不能是其他控件 其次不可以用self.xxx;里面需要使用變量再菊。
make.height.equalTo(uv.width).multipliedBy(0.5);
}];