Katedral Pillon
Katedral Pillon

Reputation: 14864

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.

Upvotes: 0

Views: 3328

Answers (2)

Sumeet
Sumeet

Reputation: 1055

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

Upvotes: 1

Gandalf
Gandalf

Reputation: 2417

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];

Upvotes: 1

Related Questions