1.上下左右spa
[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]; }
寬高code
[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]; }