UITextView caretRectForPosition wrong value for last character after press delete key
Asked Answered
C

1

6

I have a method for text changed in my web view to detect the visible rect for the current caret position.

UITextPosition *endPos = self.selectedTextRange.end;   
CGRect rect = [self caretRectForPosition:endPos];
[self scrollRectToVisible:rect animated:NO];

It works great except when I'm at the end of the document and I press the the delete key on the keyboard. In this case, it scrolls to the beginning of the document, which is unexpected.

Crease answered 17/11, 2014 at 16:50 Comment(1)
Did you find a solution for this. I have the same problem sometimes with adding newlines.Strongarm
E
1

I've had a similar problem... it seems to be a timing problem in the text view. My solution is:

A: Detect the invalid result from caretRectForPosition. In my case, the invalid coordinates seem always to be either large negative values (-1.0 seems to be i.O.!) or 'infinite' for origin.y.

B: Re-ask the text view for the caret position after a short period of time. I checked a few values for delay; 0.05 seems to be largely enough.

The code:

- (void)textViewDidChange:(UITextView *)pTextView {

    UITextPosition* endPos = pTextView.selectedTextRange.end;

    CGRect          caretRectInTextView = [pTextView caretRectForPosition:endPos];

    if ((-1.0 > CGRectGetMinY(caretRectInTextView)) ||
        (INFINITY == CGRectGetMinY(caretRectInTextView))) {
        NSLog(@"Invalid caretRectInTextView detected!");

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)),
                       dispatch_get_main_queue(),
                       ^{
                           // Recall
                           [self textViewDidChange:pTextView];
                        });
        return;


    }

    ... your code ...
}
Epexegesis answered 25/9, 2016 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.