1.如果是通過代碼添加Autolayout, 那么必須在添加約束之前禁用Autoresizing
2.禁用Autoresizing時(shí), 必須是給誰添加就禁用誰的, 也就是說如果禁用了父控件無效
3.添加約束之前, 必須保證被約束的控件已經(jīng)添加到父控件中了
self.view.translatesAutoresizingMaskIntoConstraints = NO;
Item == 第一個(gè)控件
attribute == 第一個(gè)控件的什么屬性
relatedBy == 等于/小于等于/大于等于
toItem == 第二個(gè)控件
attribute == 第二個(gè)控件的什么屬性
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];
// 寫在這里不行, 必須在設(shè)置約束之前添加
// [self.view addSubview:redView];