平時使用Masonry時命咐,一般會使用mas_updateConstraints
方法來更新約束景殷,不過該方法只能更新數(shù)值隙赁,并不會更新約束的優(yōu)先級仇祭。
??例如:
@implementation xxx
- (void)setupConstraints {
[self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
......
make.right.equalTo(self.view).offset(-50).priorityMedium();
// 靠左距離50披蕉,最高優(yōu)先級
make.left.equalTo(self.view).offset(50).priorityHigh();
}];
}
- (void)changePriority:(BOOL)isHigh {
// 更新靠左距離約束的優(yōu)先級
[self.nameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
if (isHigh) {
make.left.equalTo(self.view).offset(50).priorityHigh();
} else {
make.left.equalTo(self.view).offset(50).priorityLow();
}
}];
// 刷新布局
[self layoutIfNeeded];
}
@end
- 測試得知,這樣是不能更新約束的優(yōu)先級的乌奇,只會按初始約束來布局没讲。
- 寫著 just update the constant:只更新constant的數(shù)值。
不過有一種情況可以更新礁苗,就是修改的是同一個約束的優(yōu)先級:
.offset(xxx)
也是修改constant的數(shù)值)
如何動態(tài)更新約束的優(yōu)先級
方式一:強引用約束
- 初始化后就立馬修改的話(同一個Runloop循環(huán)內(nèi))并不會有變化试伙,適用于初始化后晚一些再更新的情況嘁信。
@interface xxx ()
@property (nonatomic, strong) MASConstraint *constraint;
@end
@implementation xxx
- (void)setupConstraints {
[self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
......
self.constraint = make.right.equalTo(self).priorityLow();
}];
}
- (void)changePriority:(BOOL)isHigh {
// 讓約束失效(內(nèi)部調(diào)用uninstall于样,從約束組內(nèi)移除)
[self.constraint deactivate];
// 重新設(shè)置優(yōu)先級
if (isHigh) {
self.constraint.priorityHigh();
} else {
self.constraint.priorityLow();
}
// 讓約束生效(內(nèi)部調(diào)用install,重新添加到約束組內(nèi))
[self.constraint activate];
// 刷新布局
[self layoutIfNeeded];
}
@end
方式二:弱引用約束【推薦】
- 相當于重新創(chuàng)建約束(不是全部潘靖,重新創(chuàng)建的是想要更新的約束)百宇,適用各種情況,能立馬更新秘豹。
@interface xxx ()
@property (nonatomic, weak) MASConstraint *constraint;
@end
@implementation xxx
- (void)setupConstraints {
[self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
......
self.constraint = make.right.equalTo(self).priorityLow();
}];
}
- (void)changePriority:(BOOL)isHigh {
// 讓約束失效(內(nèi)部調(diào)用uninstall,從約束組內(nèi)移除昌粤,由于當前約束是弱引用既绕,沒有被其他指針強引用著則會被系統(tǒng)回收)
[self.constraint uninstall];
// 重新創(chuàng)建約束(mas_updateConstraints 會把 block 內(nèi)的約束添加到約束組內(nèi)并生效)
[self.nameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
if (isHigh) {
self.constraint = make.right.equalTo(self).priorityHigh();
} else {
self.constraint = make.right.equalTo(self).priorityLow();
}
}];
// 刷新布局
[self layoutIfNeeded];
}
@end