我已经使用自动布局几天了,我试图将 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]];
更新:苹果现在希望你使用[NSLayoutConstraint activateConstraints:]
and [NSLayoutConstraint deactivateConstraints:]
而不是使用[UIView addConstraint:]
and [UIView removeConstraint:]
.
2017 年 8 月 24 日更新:
可以使用布局锚点来完成此操作的更简单版本:
[label.centerXAnchor constraintEqualToAnchor:label.superview.centerXAnchor].active = YES;
[label.centerYAnchor constraintEqualToAnchor:label.superview.centerYAnchor].active = YES;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)