3

How can I check if the text in a UITextView went to the next line due to word wrap?

I currently have code to check if the user enters a new line (from the keyboard).

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
    if ( [text isEqualToString:@"\n"] ) {
        ...
    }
    return YES;
}

1 Answers1

5

You can use the contentSize.height property of UITextView to determine how 'tall' your textview is. You can then divide by the lineHeight to figure out the number of lines. @nacho4d provided this nifty line of code that does just that:

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

Refer to this question for more info: How to read number of lines in uitextview

EDIT: So you could do something like this inside -textViewDidChange: in order to check for a line change.

int numLines = textView.contentSize.height / textView.font.lineHeight; 
if (numLines != numLinesInTextView){
    numLinesInTextView = numLines;//numLinesInTextView is an instance variable
    //then do whatever you need to do on line change
}
Community
  • 1
  • 1
bfich
  • 393
  • 2
  • 19
  • That only works if the text will be there in the beginning. In my case, the text will not be there in the beginning, the user will enter text. –  Mar 17 '15 at 23:04
  • You can use the delegate method -textViewDidChange: This gets called after the user makes changes to the text (after the delegate method you are using returns). – bfich Mar 17 '15 at 23:18
  • But the textView's height wouldn't change? –  Mar 17 '15 at 23:20
  • textView.frame.size.height doesn't change, but textView.contentSize.height does change as the user types text. If you put the line of code in my answer inside the -textViewDidChange delegate method and use NSLog(@"numLines is %d", numLines); You will see the number of lines change as you type in text. – bfich Mar 17 '15 at 23:35
  • What would the if statement be? –  Mar 17 '15 at 23:46
  • Well I'm not sure what your ultimate goal is, but you could make an instance variable named numLinesInTextView. Then do something like this (untested): `int numLines = textView.contentSize.height/textView.font.lineHeight;` `if (numLines != numLinesInTextView){``numLinesInTextView = numLines;``//do whatever you need to do on line change}` – bfich Mar 18 '15 at 16:48
  • Sorry, that's really unreadable, I'm gonna edit my answer to include this code snippet. – bfich Mar 18 '15 at 16:55