Chisx Chisx - 2 months ago 16
Objective-C Question

Get the number of lines in UILabel iOS8

I'm seeing lots of deprecated answers for this question:

How do I calculate the number of lines in use in a

UILabel
based of its set text?

I know that I need to set the
UILabel
to have bounds that resize with word wrapping. In this way, I could detect the height of my
UILabel
and adjust an
NSLayoutConstraint
for the height of my
UITableViewCell
. Basically my problem plain and simple is:

How can I determine my UILabel's number of lines in use(based of
descriptionLabel.text
) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.

Currently I have used this code:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

Answer

I solved my problem very simply with this code:

CGSize maxSize = CGSizeMake(290.0f, CGFLOAT_MAX);
CGSize requiredSize = [descriptionLabel sizeThatFits:maxSize];
[descriptionLabel setFrame:CGRectMake(15, 50, requiredSize.width, requiredSize.height)];
NSLog(@"THE HEIGHT OF THIS DESCRIPTIONLABEL IS: %f",cell.frame.size.height);