NSLayoutConstraint 使用代碼實現約束的添加和刪除

- (void)addMasonry:(NSView *)view superView:(NSView *)sView padding:(NSEdgeInsets)padding{

    view.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:sView attribute:NSLayoutAttributeTop multiplier:1.0 constant:padding.top];

    NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:sView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:padding.bottom];

    NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:sView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:padding.left];

    NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:sView attribute:NSLayoutAttributeRight multiplier:1.0 constant:padding.right];

    [sView addConstraint:top];

    [sView addConstraint:bottom];

    [sView addConstraint:left];

    [sView addConstraint:right];

}

- (void)removeMasonry:(NSView *)view superView:(NSView *)sView{

    NSArray *arr = [sView constraints];

    NSMutableArray *marr = [NSMutableArray array];

    for (NSLayoutConstraint  *constranit in arr) {

        if(constranit.firstItem == view){

            [marr addObject:constranit];

        }

    }

    [NSLayoutConstraint deactivateConstraints:marr];

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章