IOS 代碼添加約束

1.如果是通過代碼添加Autolayout, 那么必須在添加約束之前禁用Autoresizing
2.禁用Autoresizing時, 必須是給誰添加就禁用誰的, 也就是說如果禁用了父控件無效
3.添加約束之前, 必須保證被約束的控件已經添加到父控件中了
self.view.translatesAutoresizingMaskIntoConstraints = NO;

Item == 第一個控件
attribute == 第一個控件的什么屬性
relatedBy == 等于/小于等于/大于等于
toItem == 第二個控件
attribute == 第二個控件的什么屬性
multiplier == 乘以多少
constant == 加上多少

NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topCos];

Demo

UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];

redView.translatesAutoresizingMaskIntoConstraints = NO;

 // 2.1頂部約束
NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topCos];

// 2.1左邊約束
NSLayoutConstraint *leftCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
[self.view addConstraint:leftCos];

// 2.1底部約束
NSLayoutConstraint *bottomCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20];
[self.view addConstraint:bottomCos];

// 2.1右邊約束
NSLayoutConstraint *rightCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
[self.view addConstraint:rightCos];

//    寫在這里不行, 必須在設置約束之前添加
//    [self.view addSubview:redView];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容