Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust UILabel height depending on the text

Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players must use the post-apocalyptic world to their advantage, such as seeking cover behind dumpsters, pillars, cars, rubble, and other objects.

I want to resize the UILabel's height so that the text can fit in. I'm using following properties of UILabel to make the text within to wrap.

myUILabel.lineBreakMode = UILineBreakModeWordWrap; myUILabel.numberOfLines = 0; 

Please let me know if I'm not heading in the right direction. Thanks.

like image 702
Mustafa Avatar asked Jan 15 '09 11:01

Mustafa


People also ask

How do you text the height of UILabel?

text = text; label. numberOfLines = 0; [label sizeToFit]; return cell; Also use NSString 's sizeWithFont:constrainedToSize:lineBreakMode: method to compute the text's height. Show activity on this post.

How do I change the dynamic height of a label in Swift?

To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height. Let's create a label and add it as a subview to our view.


2 Answers

sizeWithFont constrainedToSize:lineBreakMode: is the method to use. An example of how to use it is below:

//Calculate the expected size based on the font and linebreak mode of your label // FLT_MAX here simply means no constraint in height CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);  CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];     //adjust the label the the new height. CGRect newFrame = yourLabel.frame; newFrame.size.height = expectedLabelSize.height; yourLabel.frame = newFrame; 
like image 89
PyjamaSam Avatar answered Oct 09 '22 14:10

PyjamaSam


You were going in the right direction. All you need to do is:

myUILabel.numberOfLines = 0; myUILabel.text = @"Enter large amount of text here"; [myUILabel sizeToFit]; 
like image 35
DonnaLea Avatar answered Oct 09 '22 13:10

DonnaLea