Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView number of lines iOS 7

In iOS 6 I used this code to get the number of lines in the UITextView:

int numLines = textView.contentSize.height / textView.font.lineHeight;

But this is not working in iOS 7. How do I get the total number of lines of the UITextView in iOS 7?

like image 709
hazem Avatar asked Oct 01 '13 18:10

hazem


2 Answers

You can use something like this. It's low performance but this is what I could figure till now.

NSString *string=textView3.text;
NSArray *array=[string componentsSeparatedByString:@"\n"];
NSLog(@"%d",array.count);
like image 182
Islam El-shazly Avatar answered Sep 23 '22 05:09

Islam El-shazly


You can do this with the UITextInputTokenizer/UITextInput protocol methods of UITextView.

id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *pos = textView.endOfDocument; int lines = 0;

while (true){
    UITextPosition *lineEnd = [tokenizer positionFromPosition:pos toBoundary:UITextGranularityLine inDirection:UITextStorageDirectionBackward];

    if([textView comparePosition:pos toPosition:lineEnd] == NSOrderedSame){
        pos = [tokenizer positionFromPosition:lineEnd toBoundary:UITextGranularityCharacter inDirection:UITextStorageDirectionBackward];

        if([textView comparePosition:pos toPosition:lineEnd] == NSOrderedSame) break;

        continue;
    }

    lines++; pos = lineEnd;
}

//lines--; // Compensation for extra line calculated (??)

(GIST)

like image 4
mattsven Avatar answered Sep 20 '22 05:09

mattsven