1、讓控件添加到父控件中spa
/** 添加藍色的View到父控件上*/ip
UIView *blueView = [[UIView alloc]init];it
blueView.backgroundColor = [UIColor blueColor];io
[blueView setTranslatesAutoresizingMaskIntoConstraints:NO];di
[self.view addSubview:blueView];view
2、給控件添加一條約束vi
/** 添加左邊的約束 blueView 的左邊 等於self.view的左邊 *1.0 + 50的偏移量 */ant
NSLayoutConstraint *blueConstraintLeft = [NSLayoutConstraintco
constraintWithItem:blueView background
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:50];
/** 添加右邊的約束*/
NSLayoutConstraint *blueConstraintRight = [NSLayoutConstraint
constraintWithItem:blueView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:redView
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:-50];
[self.view addConstraint:blueConstraintRight];
一句話就是:誰的哪一個位置等於(/大於等於/小於等於)誰的哪一個位置乘個係數+上個修正值(最左邊向右修正是正數 ,最右邊向左修正是負數)
3、把約束添加到父視圖中
[self.view addConstraint:blueConstraintLeft];// 添加約束到父視圖中