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?
Asked
Active
Viewed 4,378 times
1 Answers
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
-
undefined variable width? – user4807387 Apr 22 '15 at 06:56
-
@user4807387 `width` is the width of label because width of the label must be known for both of them to work. – Ozgur Vatansever Apr 22 '15 at 18:18
-
how to acces that? label.width isn't valid – user4807387 Apr 22 '15 at 18:23
-
I'm assuming you mean label.bounds.size.width, but am really not sure – user4807387 Apr 23 '15 at 05:52
-
I will upvote your question if you give me an answer and explanation to my question about width. – user4807387 Apr 23 '15 at 05:56
-
@user4807387 `width` is the maximum width that label can take, probably the width of its superview. – Ozgur Vatansever Jul 13 '15 at 05:26