如何使用自动布局在屏幕中水平和垂直居中UILabel?

我一直在使用汽车布局几天,我试图将UILabel垂直和水平地放在屏幕中,但我没有太多运气让标签居中。

我希望能够实现如下所示的内容,

--------------- | | | | | | | | | Label | | | | | | | | | | SIGNIN REG | --------------- 

我向UILabel添加了以下约束,

 NSLayoutConstraint *myLabelConstraintHeight = [NSLayoutConstraint constraintWithItem:myLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:100]; [myLabel addConstraint:myLabelConstraintHeight]; NSLayoutConstraint *myLabelConstraintWidth = [NSLayoutConstraint constraintWithItem:myLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:100]; [myLabel addConstraint:myLabelConstraintWidth]; 

 NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:label.superview attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]; NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:label.superview attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]; // No longer using [label addConstraints:@[centerX, centerY]; [NSLayoutConstraint activateConstraints:@[centerX, centerY]]; 

更新:Apple现在希望您使用[NSLayoutConstraint activateConstraints:][NSLayoutConstraint deactivateConstraints:]而不是使用[UIView addConstraint:][UIView removeConstraint:]

更新8/24/17:

可以使用布局锚点来完成更简单的版本:

 [label.centerXAnchor constraintEqualToAnchor:label.superview.centerXAnchor].active = YES; [label.centerYAnchor constraintEqualToAnchor:label.superview.centerYAnchor].active = YES;