用 AutoLayout 排版時常會遇到一個需求:專案跑到某個階段,需要動態修改某個約束的值,例如把 x 或 y 挪一下。與其改常數,有時候更乾淨的做法是直接把不需要的約束移除。下面整理三種常見的刪除方式。
先宣告一個別名,讓後面的程式碼讀起來更清楚(本質上就是 NSLayoutConstraint):
typedef NSLayoutConstraint ZLLayoutConstraint;
注意約束可能掛在自己身上,也可能掛在 superview 上,兩邊都要清一次才算乾淨。
#pragma mark - remove view to superView autoLayout
- (void)removeAllAutoLayout {
[self removeConstraints:self.constraints];
for (ZLLayoutConstraint *constraint in self.superview.constraints) {
if ([constraint.firstItem isEqual:self]) {
[self.superview removeConstraint:constraint];
}
}
}
實務上更推薦先把要移除的約束用 IBOutlet 或屬性持有起來,再呼叫 removeConstraint:,比遍歷比對更直覺也比較不容易出錯。以下示範遍歷比對的寫法:
#pragma mark - remove single constraint
- (void)removeAutoLayout:(ZLLayoutConstraint *)targetConstraint {
for (ZLLayoutConstraint *constraint in self.superview.constraints) {
if ([constraint isEqual:targetConstraint]) {
[self.superview removeConstraint:constraint];
}
}
}
#pragma mark - remove constraints
- (void)removeAutoLayoutConstraints:(NSArray *)constraints {
for (ZLLayoutConstraint *constraint in constraints) {
for (ZLLayoutConstraint *superViewConstraint in self.superview.constraints) {
if ([superViewConstraint isEqual:constraint]) {
[self.superview removeConstraint:constraint];
}
}
}
}
約束被移除後,千萬記得呼叫 [self setNeedsLayout] 與 [self layoutIfNeeded],畫面才會立刻更新;若同時有多個約束變動,建議放進同一個 layoutIfNeeded 批次處理,避免版面一閃一閃。另外,若要移除的是「某個 View 相關的所有約束」,把判斷條件同時檢查 secondItem 會更嚴謹。