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).
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()
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];
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With