1.最简单用法
//简单添加控件
UIButton *button = [[UIButton alloc] init];
button.backgroundColor = [UIColor redColor];
//必须说明,以前一下转化就不要用了,就是直接的自动布局.
button.translatesAutoresizingMaskIntoConstraints = NO;
[button setTitle:@"自动布局" forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
//如果要用到父类的约束,就要先添加
[self.view addSubview:button];
//添加width约束
// constraintWithItem:自己控件 attribute:约束 relatedBy:等于还是大于 toItem:别人控件 attribute:约束 multiplier:乘以多少 constant:加多少
//这个约束是,自己宽是300.0
NSLayoutConstraint *with_Constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:300.0];
[button addConstraint:with_Constraint];
//高度的约束
NSLayoutConstraint *height_Constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:300];
[button addConstraint:height_Constraint];
//边距的约束,右边的约束 这个约束和父类有关系,所以就父类加约束
NSLayoutConstraint *right_Constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10];
[self.view addConstraint:right_Constraint];
//下面的约束
NSLayoutConstraint *bottom_Constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10];
[self.view addConstraint:bottom_Constraint];