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 ...
}