nburk nburk - 4 months ago 10
iOS Question

How to find actual number of lines of UILabel?

How can I find the actual number of lines of a

UILabel
after I have initialized it with a
text
and a
font
? I have set its
numberOfLines
property to
0
, 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
text
?

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
boundingRectWithSize
or
sizeWithFont
,...

Answer

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);