您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 如何動態刪除 AutoLayout 約束:刪全部、刪單個、刪多個

編輯:iOS 開發綜合

用 AutoLayout 排版時常會遇到一個需求:專案跑到某個階段,需要動態修改某個約束的值,例如把 x 或 y 挪一下。與其改常數,有時候更乾淨的做法是直接把不需要的約束移除。下面整理三種常見的刪除方式。

先宣告一個別名,讓後面的程式碼讀起來更清楚(本質上就是 NSLayoutConstraint):

typedef NSLayoutConstraint ZLLayoutConstraint;

一、移除該 View 的所有約束

注意約束可能掛在自己身上,也可能掛在 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 會更嚴謹。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved