Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView providing incorrect caret rect

Tags:

ios

uitextview

My UITextView delegate is logging the caret position using the following:

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;
    NSLog(@"cursor: %@", NSStringFromCGPoint(cursorPosition));
}

But the reported position is always inaccurate. Specifically, it reports the previous cursor position - for example, if I click once inside the text view at position (x,y) then outside, then back inside at (x2,y2), on the second click the (x,y) coordinates are logged.

In fact, the selectedTextRange is the issue - the previous range is reported.

What am I missing? I don't see another delegate method I can use instead.

like image 497
Ben Packard Avatar asked Oct 09 '14 03:10

Ben Packard


2 Answers

Value of selectedTextRange will be older only as the editing has just began, it has not changed yet. As you are calculating the cursorPostion with selected text, old values will lead to old position. So we need to calculate the new position inside a different delegate which reports after the selection changes. You will get correct readings with below mentioned code. Hope it helps

-(void)textViewDidChangeSelection:(UITextView *)textView
{
    CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;
    NSLog(@"cursor start: %@", NSStringFromCGPoint(cursorPosition));
}
like image 200
Gandalf Avatar answered Sep 18 '22 10:09

Gandalf


It's pretty gross but one solution is to introduce a short delay before reading calling the method:

UITextView *textView = note.object;

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;
    NSLog(@"cursor: %@", NSStringFromCGPoint(cursorPosition));
});
like image 27
Ben Packard Avatar answered Sep 18 '22 10:09

Ben Packard