Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making multiline UILabel to start text from the top not the middle

I have a little problem with multiline UILabel, my UILabel text like starts from the middle strangely and it goes up when new lines arrive so that the last line is on the middle always. I want it to behave like a normal textview, starting from top and lines going under each other, first line staying on top. Sorry if I explained it badly, I can try to elaborate if needed! Thanks in advance!

like image 965
Samuli Lehtonen Avatar asked Mar 03 '11 21:03

Samuli Lehtonen


People also ask

How do I align text to the top of UILabel Swift?

In UILabel vertically text alignment is not possible. But, you can dynamically change the height of the label using sizeWithFont: method of NSString , and just set its x and y as you want. You can use UITextField . It supports the contentVerticalAlignment peoperty as it is a subclass of UIControl .

How do you make UILabel two lines?

To set the number of lines we want our UILabel to support we will use a numberOfLines property. For example, to make UILabel support two lines, we will set the numberOfLines property to 2.

What is UILabel?

A view that displays one or more lines of informational text.


1 Answers

You can use the sizeWithFont:constrainedToSize:lineBreakMode: method on NSString to figure out the height of a block of text given a font and a constrained width. You would then update the frame of your label to be just large enough to encompass the text.

CGSize textSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(20.0f, 20.0f, textSize.width, textSize.height);
like image 138
Mark Adams Avatar answered Oct 18 '22 02:10

Mark Adams