简体   繁体   中英

Vertically center UILabel in parent UIView

How do I vertically (y-axis) center a UILabel inside its parent UIView without changing the horizontal position of the UILabel?

The following is not it (it changes the x-axis):

[self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]

Again, I am looking to center along the y-axis.

CGPoint center = self.label.center;
center.y = view.frame.size.height / 2;
[self.label setCenter:center];

Swift Answer..

var center : CGPoint = self.titleLbl.center
        center.y = self.frame.size.height / 2
        self.titleLbl.center = center

I would rather recommend to apply autolayout constraints in this case. The below constraint will align is vertically in center of parent view.In 2nd constraint i am keeping a value of 20 as x coordinate. You can replace it with your own value.

NSLayoutConstraint *constraintY = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeCenterY
                      relatedBy:NSLayoutRelationEqual toItem:view
                      attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
[view addConstraint:constraintY];
NSLayoutConstraint *constraintX = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeLeading
                          relatedBy:NSLayoutRelationEqual toItem:view
                          attribute:NSLayoutAttributeLeading multiplier:1.0 constant:20.0];
[view addConstraint:constraintX];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM