1.上下左右
[tipsLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; { id view1 = tipsLabel; id view2 = self; //子view的上边缘离父view的上边缘 NSLayoutConstraint *contraint1 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]; //子view的左边缘离父view的左边缘 NSLayoutConstraint *contraint2 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]; //子view的下边缘离父view的下边缘 NSLayoutConstraint *contraint3 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-btnHeight]; //子view的右边缘离父view的右边缘 NSLayoutConstraint *contraint4 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]; //把约束添加到父视图上 NSArray *array = [NSArray arrayWithObjects:contraint1, contraint2, contraint3, contraint4, nil,nil]; [self addConstraints:array]; }
宽高
[imgv setTranslatesAutoresizingMaskIntoConstraints:NO]; { id view1 = imgv; id view2 = self.view; id viewNil = nil; // NSLayoutConstraint *contraint1 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:viewNil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:size.width]; [imgv addConstraint:contraint1]; // NSLayoutConstraint *contraint2 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:viewNil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:size.height]; [imgv addConstraint:contraint2]; //子view的下边缘离父view的下边缘 NSLayoutConstraint *contraint3 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]; //子view的右边缘离父view的右边缘 NSLayoutConstraint *contraint4 = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]; //把约束添加到父视图上 NSArray *array = [NSArray arrayWithObjects:contraint3, contraint4, nil,nil]; [self.view addConstraints:array]; }