Is there a way to "top align" a UILabel, that is make text stick to top of label view? As opposed to center aligned vertically, or float in the center of the view, as is the default?
Here is an image of three labels, aligned left, right and center, and a UITextView that is aligned center and top. The text of the textView sticks to the top regardless of the vertical size of the view. Can I do the same thing with a label?
There is no way to set the vertical alignment of a
UILabel by default in iOS. Instead, you will want to use one of the
sizeWithFont methods provided by
NSString. Which one you use depends on whether you want a multi-line or single-line label.
sizeWithFont:forWidth:lineBreakMode: can be used for single-line labels, while
sizeWithFont:constrainedToSize:lineBreakMode: can be used for multi-line labels. You can easily load the font parameter with the
font property of the label in question. You can look here for some more details on using these functions: http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html
These methods will return a
CGSize struct with the minimum size for your label based on the text in the
NSString. Once you have the correct size for the label, you can easily place it at the top of your superview and it will appear to be top-aligned.