uilabel 垂直居中对齐,如何使用自动布局在屏幕上水平和垂直居中放置UILabel?

I've been using auto layout for a couple of days now, and I am trying to center a UILabel in the screen vertically and horizontally, but I am not having much luck with getting the label centered.

I am hoping to achieve something that looks like the following,

---------------

| |

| |

| |

| |

| Label |

| |

| |

| |

| |

| SIGNIN REG |

---------------

I added the following constraints to the 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]];

UPDATE: Apple now wants you to use [NSLayoutConstraint activateConstraints:] and [NSLayoutConstraint deactivateConstraints:] instead of using [UIView addConstraint:] and [UIView removeConstraint:].

UPDATE 8/24/17:

A simpler version of this can be done using layout anchors:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值