





















#import "ViewController.h" @interface ViewController () @property (strong,nonatomic)UIView *view1; @property (strong,nonatomic)UIView *view2; @end
//创建view1 self.view1 = [[UIView alloc]init]; self.view1.backgroundColor = [UIColor redColor]; self.view1.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:self.view1]; //创建view2 self.view2 = [[UIView alloc]init]; self.view2.backgroundColor = [UIColor yellowColor]; self.view2.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:self.view2];
//view1的x坐标和父视图的x坐标的关系 NSLayoutConstraint *LCLfet = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:20];
4.创建view1和父视图的y坐标之间的约束
//view1的y坐标和父视图的y坐标的关系 NSLayoutConstraint *LCBottom = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20];
//view1和view2等宽 NSLayoutConstraint *lcEqualWitdth = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view2 attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
//view1和view2等高 NSLayoutConstraint *lcEqualHeight = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view1 attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0];
//view2的x坐标和父视图的x坐标的关系 NSLayoutConstraint *LCRight = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:-20];
8.创建view2和父视图的y坐标之间的约束
//view2的y坐标和父视图的y坐标的关系 NSLayoutConstraint *LCBottom2 = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20];
//view1和view2的水平间距 NSLayoutConstraint *lcGap = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view1 attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:20];
//在父视图中添加约束 [self.view addConstraints:@[LCLfet,LCBottom,LCRight,LCBottom2,lcEqualHeight,lcEqualWitdth,lcGap]];
//view1固定的高度 NSLayoutConstraint *lcFixedHeight = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:200];
//在view1上添加约束 [self.view1 addConstraint:lcFixedHeight];
原文:http://www.cnblogs.com/XYQ-208910/p/4898534.html