Trip
Trip

Reputation: 27124

Attempting at centering UILabel in Swift

I'm attempting at centering a UILabel, but it doesn't seem to be responding. This is my intuitive code, though I'm certain it's far from the best way to do this..

    let sanskritLabel  = UILabel(frame: CGRectZero)
        sanskritLabel.text = page!.sanskrit!
        sanskritLabel.frame.size.width  = self.view.frame.size.width
        sanskritLabel.textAlignment     = .Center
        sanskritLabel.numberOfLines     = 0
        sanskritLabel.layer.borderColor       = UIColor.cyanColor().CGColor
        sanskritLabel.layer.borderWidth       = 3.0;
        sanskritLabel.center            = CGPointMake(self.view.frame.width/2, verse.frame.origin.y + chapterStringSize.height + 20)
        sanskritLabel.sizeToFit()

I used this on other UILabels below this one, and they seem to center just fine. In this case, this UILabel sanskritLabel , appears floated to the left :

enter image description here

Which is strange because I'm explicitly saying that the width should be self.view.frame.size.width , but it seems to be either ignoring that.

I imagine that if the width was set to be exactly as I'm declaring it ( 375 ), then the text would be centered fine because of the .textAlignment attribute.

Any idea why this isn't working?

Upvotes: 0

Views: 98

Answers (2)

David Berry
David Berry

Reputation: 41246

As Jonah said, you're resizing the view with sizeToFit, after setting the frame with center. so when the view is resized, it changes the size but keeps the same origin. To fix the problem call sizeToFit before you set the center:

sanskritLabel.sizeToFit()
sanskritLabel.center = CGPointMake(self.view.frame.width/2, verse.frame.origin.y + chapterStringSize.height + 20)

Upvotes: 4

Jonah
Jonah

Reputation: 17958

You are calling sizeToFit which updates the label's frame:

- sizeToFit
Resizes and moves the receiver view so it just encloses its subviews.

Upvotes: 1

Related Questions