nburk nburk - 1 year ago 56
iOS Question

How to find actual number of lines of UILabel?

How can I find the actual number of lines of a

after I have initialized it with a
and a
? I have set its
property to
, so it will expand to however many lines are necessary. But then, how can I find out how many lines it finally got after I set its

I found similar questions, but none seems to provide a concise answer and it seems to me that it must be really easy to get it without any overhead on juggling around with the

Answer Source

Firstly set text in UILabel

First Option :

Firstly calculate height for text according to font :

NSInteger lineCount = 0;
CGSize labelSize = (CGSize){yourLabel.frame.size.width, MAXFLOAT};
CGRect requiredSize = [self boundingRectWithSize:labelSize  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: yourLabel.font} context:nil];

Now calculate number of lines :

int charSize = lroundf(yourLabel.font.leading);
int rHeight = lroundf(requiredSize.height);
lineCount = rHeight/charSize;
NSLog(@"No of lines: %i",lineCount);

Second Option :

 NSInteger lineCount = 0;
 CGSize textSize = CGSizeMake(yourLabel.frame.size.width, MAXFLOAT);
 int rHeight = lroundf([yourLabel sizeThatFits:textSize].height);
 int charSize = lroundf(yourLabel.font.leading);
 lineCount = rHeight/charSize;
 NSLog(@"No of lines: %i",lineCount);