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:

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:

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()
}

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


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


Need Your Help

MFC ActiveX CShockwaveflash element. How to disable the context menu?

c++ flash mfc activex contextmenu

So i'm using the ActiveX CShockwaveflash element in my MFC application and i want to disable the context menu.

Retrieve values using a self join query

mysql

I want to retrieve records where the albumid is not found on the parent_albumid and where the parent_albumid is NULL