-7

Is there is anyway to check the number of lines in a UITextview?

I searched on the internet but I found nothing.

AFB
  • 550
  • 2
  • 8
  • 25

3 Answers3

3

For iOS7, a version that take care that you can have differents font (and font size) in your UITextView :

- (NSUInteger)numberOfLines
{
    NSLayoutManager *layoutManager = [textView layoutManager];
    NSUInteger index, numberOfLines;
    NSRange glyphRange = [layoutManager glyphRangeForTextContainer:[textView textContainer]];
    NSRange lineRange;

    for (numberOfLines = 0, index = glyphRange.location; index < glyphRange.length; numberOfLines++){
        (void) [layoutManager lineFragmentRectForGlyphAtIndex:index
                                               effectiveRange:&lineRange];
        index = NSMaxRange(lineRange);
    }
    return numberOfLines;
}
Emmanuel
  • 2,897
  • 1
  • 14
  • 15
  • For more info, Apple docs for this method is here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextLayout/Tasks/CountLines.html – James Kuang Jan 11 '15 at 01:24
0

For Count the number of lines of text

int numLines = textView.contentSize.height / textView.font.lineHeight;
NSLog(@"number of line - %d", numLines);

And for iOS 7 see this Question/Answer.

EDIT for iOS < 7:

This is proper answer

UIFont *myFont = [UIFont boldSystemFontOfSize:13.0]; // your font with size
CGSize size = [textView.text sizeWithFont:myFont  constrainedToSize:textView.frame.size  lineBreakMode:UILineBreakModeWordWrap]; // default mode
int numLines = size.height / myFont.lineHeight;
NSLog(@"number of line - %d", numLines);
Community
  • 1
  • 1
iPatel
  • 46,010
  • 16
  • 115
  • 137
0

Although you didn't search a lot, here's a way :

CGSize size = [myString sizeWithFont:textView.font constrainedToSize:CGSizeMake(textView.frame.size.width,999) lineBreakMode:UILineBreakModeWordWrap];
int numLines = size.height / textView.font.lineHeight;
rdurand
  • 7,342
  • 3
  • 39
  • 72
  • `sizeWithFont` is deprecated, consider using `sizeWithAttributes` and `boundingRectWithSize`. – JMarsh Feb 27 '14 at 13:39
  • @JMarsh, sizeWithFont:constrainedToSize:lineBreakMode: is deprecated in iOS 7, but is the **CORRECT** way to do it in iOS < 7 (the alternative, boundingRectWithSize:options:attributes:context:, is ONLY available in iOS 7.) Thus rdurand's approach is quite reasonable for an app that runs on iOS < 7 as well as iOS 7. – Duncan C Feb 27 '14 at 13:51
  • @DuncanC : thanks (lol). JMarsh : you're correct, and there certainly are other ways, this is *a* way to do it. – rdurand Feb 27 '14 at 14:15