4

A lot of the old solutions to this same question are deprecated (UILineWordWrap, to name one deprecated one). I also found some of them unreliable. So, in IOS 8, how should I find the number of lines in a uilabel?

user4807387
  • 69
  • 1
  • 6

1 Answers1

6

As of iOS8, you can use [NSString boundingRectWithSize:options:attributes] to get the height of a given string.

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = label.lineBreakMode;
NSDictionary *attributes = @{NSFontAttributeName: label.font, NSParagraphStyleAttributeName: paragraphStyle.copy};
NSInteger options = NSStringDrawingUsesLineFragmentOrigin;

CGRect rect = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:options attributes:attributes context:nil];
NSInteger numberOfLines = floor(ceilf(rect.size.height) / label.font.lineHeight);

As an alternative approach; you can also make use of [UILabel: sizeToFit] method as follows if you already set the width of your label:

label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
[label sizeToFit];
NSInteger numberOfLines = floor(ceilf(CGRectGetHeight(label.frame)) / label.font.lineHeight);
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119