2015-04-30 47 views
2

我已经使用了几天的自动布局,并且我试图在屏幕中垂直和水平居中放置一个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]; 
+1

NSLayoutConstraint constraintWithItem:myLabel 属性:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:myLabel。 superview 属性:NSLayoutAttributeCenterX 乘数:1.f常数:0.f]; 对Y中心做同样的工作 – Vig

回答

7
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:][NSLayoutConstraint deactivateConstraints:]而不是使用[UIView addConstraint:][UIView removeConstraint:]

更新17年8月24日:

这方面的一个简单的版本可以使用布局锚来完成:

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

如果我使用'self.view addSubview:myLabel]'将'myLabel'添加到视图hiearchy,它会有所作为吗? – Chris

+1

不,它不会,只要你添加标签作为子视图然后添加约束。否则,label.superview可能为零。 – keithbhunter

+0

感谢您的好评。 – Chris

相关问题