iosobjective-cnsstringuitextview

Detect moment when newline starts in UITextView


I try to detect when carriage goes at new line in UITextView. I can detect it by comparison total later width with UITextView width:

CGSize size = [textView.text sizeWithAttributes:textView.typingAttributes];
if(size.width > textView.bounds.size.width)
      NSLog (@"New line");

But it dose not work proper way because -sizeWithAttributes:textView returns only width of letters without indentation width. Help please solve this.


Solution

  • This is how I would do it:

    Sample code:

    CGRect previousRect = CGRectZero;
    - (void)textViewDidChange:(UITextView *)textView{
    
        UITextPosition* pos = yourTextView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
        CGRect currentRect = [yourTextView caretRectForPosition:pos];
    
        if (currentRect.origin.y > previousRect.origin.y){
                //new line reached, write your code
            }
        previousRect = currentRect;
    
    }
    

    Also, you should read the documentation for UITextInput protocol reference here. It is magical, I'm telling you.

    Let me know if you have any other issues with this.