1 #import "RootViewController.h" 2 3 @interface RootViewController () 4 5 @end 6 7 @implementation RootViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 // Do any additional setup after loading the view. 12 13 #pragma mark - label的约束 14 // 如果想通过约束来控制视图的位置大小,不需要设置frame 15 UILabel *label = [[UILabel alloc] init]; 16 17 // 禁止自动转换 18 label.translatesAutoresizingMaskIntoConstraints = NO; 19 20 label.backgroundColor = [UIColor redColor]; 21 22 // 视图添加到父视图上之后,才能进行布局 23 [self.view addSubview:label]; 24 25 26 // 进行约束布局 27 // 距离上面50 28 /* 29 constraintWithItem:要约束的视图对象 30 第一个attribute:要约束视图对象的属性 31 relatedBy:和参照视图的关系 32 toItem:参照视图的对象 33 第二个attribute:参照视图对象的属性 34 multiplier:比例 35 constant:距离的数值 36 */ 37 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:50]]; 38 39 // 距离左边100 40 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:100]]; 41 42 // 距离右边100 43 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:-100]]; 44 45 // 距离底部500 46 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-500]]; 47 48 #pragma mark - label1的约束 49 50 UILabel *label1 = [[UILabel alloc] init]; 51 label1.translatesAutoresizingMaskIntoConstraints = NO; 52 label1.backgroundColor = [UIColor greenColor]; 53 [self.view addSubview:label1]; 54 55 56 // 布局label1 57 [self.view addConstraints:@[ 58 // 距离上边50 59 [NSLayoutConstraint constraintWithItem:label1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeBottom multiplier:1 constant:50], 60 61 // 和label左边对齐 62 [NSLayoutConstraint constraintWithItem:label1 attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeLeading multiplier:1 constant:0], 63 64 // 和label右边对齐 65 [NSLayoutConstraint constraintWithItem:label1 attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeTrailing multiplier:1 constant:0], 66 67 // 高度60 68 [NSLayoutConstraint constraintWithItem:label1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:60] 69 70 ]]; 71 72 } 73 74 @end