Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uilabel

swift

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

like image 390
user3766930 Avatar asked Mar 15 '16 17:03

user3766930


People also ask

How do I align text in a label?

Solutions with CSS properties Then, we set the display of the <label> element to "inline-block" and give a fixed width. After that, set the text-align property to "right", and the labels will be aligned with the inputs on the right side.


2 Answers

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()
}
like image 166
Lluis Gerard Avatar answered Nov 02 '22 14:11

Lluis Gerard


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

like image 37
Ben Sullivan Avatar answered Nov 02 '22 12:11

Ben Sullivan