Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView (editing) - detecting that next line event occured

I have a UITextView which is editable. Now I have a requirement which requires me to find (as and when I keep typing) as to when the next line has begun (maybe due to me hitting the return key, or an auto wordwrap linebreak). Is there any notification which can be obtained to figure out when the next line has started while typing?

I tried searching for solutions to find out cursor positions within a textview but using selectedRange and the location properties to find it out does not help me. There is no correlation at all between the location value and a new line. The location value just keeps increasing on typing. Any ideas?

Thanks!

like image 443
Bourne Avatar asked Feb 02 '11 11:02

Bourne


3 Answers

The following delegate is called whenever a new text is entered in textView.

Set the delegate for UITextView, then code as follows

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
    if ( [text isEqualToString:@"\n"] ) {
        //Do whatever you want
    }
    return YES;
}
like image 157
KingofBliss Avatar answered Oct 31 '22 23:10

KingofBliss


For Swift use this

previousRect = CGRectZero

 func textViewDidChange(textView: UITextView) {

        var pos = textView.endOfDocument
        var currentRect = textView.caretRectForPosition(pos)
        if(currentRect.origin.y > previousRect?.origin.y){
            //new line reached, write your code
        }
        previousRect = currentRect

    }

For Objective C

CGRect previousRect = CGRectZero;
- (void)textViewDidChange:(UITextView *)textView{

    UITextPosition* pos = textView.endOfDocument;
    CGRect currentRect = [textView caretRectForPosition:pos];

    if (currentRect.origin.y > previousRect.origin.y){
            //new line reached, write your code
        }
    previousRect = currentRect;

}
like image 45
Sourav Gupta Avatar answered Nov 01 '22 00:11

Sourav Gupta


Will detect line changes from anything to hitting "return", backspacing to reduce line-count, typing till the end of the line and a word-wrap occurs, etc. (*Note: MUST adjust variables for font size, I recommend not using hard coded numbers like in my example below).

previousNumberOfLines = ((hiddenText.contentSize.height-37+21)/(21));//numbers will change according to font size
NSLog(@"%i", previousNumberOfLines);
like image 45
Albert Renshaw Avatar answered Oct 31 '22 22:10

Albert Renshaw