I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label.
How do I vertically align the text to always be at the top of the UILabel?

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no way to set the vertical-align on a
UILabel, but you can get the same effect by changing the label’s frame. I’ve made my labels orange so you can see clearly what’s happening.Here’s the quick and easy way to do this:
If you have a label with longer text that will make more than one line, set
numberOfLinesto0(zero here means an unlimited number of lines).Longer Version
I’ll make my label in code so that you can see what’s going on. You can set up most of this in Interface Builder too. My setup is a View-Based App with a background image I made in Photoshop to show margins (20 points). The label is an attractive orange color so you can see what’s going on with the dimensions.
Some limitations of using
sizeToFitcome into play with center- or right-aligned text. Here’s what happens:The label is still sized with a fixed top-left corner. You can save the original label’s width in a variable and set it after
sizeToFit, or give it a fixed width to counter these problems:Note that
sizeToFitwill respect your initial label’s minimum width. If you start with a label 100 wide and callsizeToFiton it, it will give you back a (possibly very tall) label with 100 (or a little less) width. You might want to set your label to the minimum width you want before resizing.Some other things to note:
Whether
lineBreakModeis respected depends on how it’s set.NSLineBreakByTruncatingTail(the default) is ignored aftersizeToFit, as are the other two truncation modes (head and middle).NSLineBreakByClippingis also ignored.NSLineBreakByCharWrappingworks as usual. The frame width is still narrowed to fit to the rightmost letter.Mark Amery gave a fix for NIBs and Storyboards using Auto Layout in the comments:
My Original Answer (for posterity/reference):
This uses the
NSStringmethodsizeWithFont:constrainedToSize:lineBreakMode:to calculate the frame height needed to fit a string, then sets the origin and width.Resize the frame for the label using the text you want to insert. That way you can accommodate any number of lines.