Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel sizeToFit not working properly. Using setNumberOfLines doesn't work. Need variable height function to work

I am trying to show a variable height amount of text through UILabel.
I set everything up through a combination of Xcode's storyboard and coding directly into the implementation files.

Here is the code:

CGRect labelFrame = CGRectMake(20, 20, 280, 800);
descriptionLabel.frame = labelFrame;
NSString *description = self.spell[@"description"];
descriptionLabel.text = description;
[descriptionLabel setNumberOfLines:0];
[descriptionLabel sizeToFit];

I have tried changing the wordwrap functions and tried playing around with a lot of different settings but to no avail.

Is there something specific that needs to be done in the storyboard?
Is the structure of my view->label important?
I have it so that the labels are in a view (which takes up the whole screen).

like image 483
user2050812 Avatar asked Feb 07 '13 12:02

user2050812


3 Answers

I'm using SWIFT and I faced the same issue. I fixed it after I added layoutIfNeeded(). My code is as follows:

self.MyLabel.sizeToFit()
self.MyLabel.layoutIfNeeded()
like image 194
Ken Seow Avatar answered Nov 12 '22 04:11

Ken Seow


You do not need to calculate the heights manually. For variable height, set the height of the label to 0 before calling sizeToFit, like this.

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 0)];
label.numberOfLines = 0;
label.text = @"Some long piece of text...";

[label sizeToFit];
like image 27
1actobacillus Avatar answered Nov 12 '22 05:11

1actobacillus


Here is my solution for any problem such as yours (dynamic height):

NSString *description = @"Some text";

CGSize dynamicSize = [[description sizeWithFont:[UIFont fontWithName:@"FONT_NAME" size:14] constrainedToSize:CGSizeMake(300, 10000)]; //the width should be the one you need and just put in a very big height so that anything you would put in here would fit
//dynamicSize is now the exact size you will need, with the fixed width and the height just enough so that all the text will fit.

UILabel *someLabel = [[UILabel alloc] initWithFrame:CGRectMake:(0, 0, dynamicSize.width, dynamicSize.height)];
someLabel.font = YOUR_FONT;
someLabel.numberOfRows = 10 //You should calculate how many rows you need by dividing dynamicSize.height to the height of one row (should also take into account the padding that your UILabel will put between rows

This is, in my opinion the safest way to determine the needed height. Also, as far as I know, calling sizeToFit will not change it's size if it is already big enough to hold all the text.(will not make it smaller...just bigger if it needs to but it will not add more lines)

like image 1
Andrei Filip Avatar answered Nov 12 '22 05:11

Andrei Filip