user3766930
user3766930

Reputation: 5829

how can I align the text of my label in swift so that it starts in the top left corner of the label?

I have a textfield with lines property set to 0, so that when the text is longer it will automatically fill all the necessary space. But when the string is short, it is automatically placed in the middle of the label, it looks like this:

enter image description here

Is there a way (or maybe a property to set) of putting this text in the top left corner? This is my attribute inspector for that label:

enter image description here

Upvotes: 8

Views: 17855

Answers (3)

Lluis Gerard
Lluis Gerard

Reputation: 1661

If you are using Autolayout you can try to set only top, left and right constraints without any height constraint. That should work, but if you are not using Autolayout or you are having trouble changing these constraints you can also call label.sizeToFit() after setting the text.

To call sizeToFit, if you are setting the text on viewDidLoad or in the Storyboard itself, you can call it on viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {
    label.sizeToFit()
}

Upvotes: 10

Ben Sullivan
Ben Sullivan

Reputation: 2154

This really should be a default option in Xcode, you could use the work around in the other answer or alternatively just use a TextView which by default gives you the top left behaviour you're looking for

Upvotes: 1

Russell
Russell

Reputation: 5554

you would think this would be easy, but it appears to not be. There's a good solution outlined here how to set top left alignment for UILabel

Upvotes: 0

Related Questions