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
Following up on @Prince's answer, I now implemented a category on UILabel
as follows (note that I corrected some minor syntax mistakes in his answer that wouldn't let the code compile):
#import
@interface UILabel (Util)
- (NSInteger)lineCount;
@end
#import "UILabel+Util.h"
@implementation UILabel (Util)
- (NSInteger)lineCount
{
// Calculate height text according to font
NSInteger lineCount = 0;
CGSize labelSize = (CGSize){self.frame.size.width, FLT_MAX};
CGRect requiredSize = [self.text boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: self.font} context:nil];
// Calculate number of lines
int charSize = self.font.leading;
int rHeight = requiredSize.size.height;
lineCount = rHeight/charSize;
return lineCount;
}
@end