我尝试获取UITextView插入位置。为此,我使用caretRectForPosition
方法。手动输入文本时工作正常。但是如果我在文本视图中插入文本,该方法将返回无意义的负坐标。
以下是我的代码的主题部分:
- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// Truncated part of the code: text preparation, objects declaration and so on.
// Past calculated text into the textView
textView.text = newTextViewText;
// Calculate cursor position to avoid its jump to the end of the string. This part works fine.
NSInteger cursorPosition = range.location + allowedText.length;
textView.selectedRange = NSMakeRange(cursorPosition, 0);
// Try to get caret coordinates. It doesn't work properly when text is pasted
cursorCoordinates = [textView caretRectForPosition:textView.selectedTextRange.end].origin;
}
我想在文本插入后有一些延迟,当我尝试获取光标坐标时已经处理了字符串。但我不知道在哪里寻找这个时间差距来源。有什么想法吗?
更新:我发现当插入文本放在2行以上时会发生这种情况。仍然不知道如何解决它。
答案 0 :(得分:2)
我遇到了同样的问题......是的,这似乎是一个时间问题。 我的解决方案是:
答:检测来自caretRectForPosition的无效结果。在我的例子中,无效坐标似乎总是要么是大的负值(-1.0似乎是i.O.!)或者是origin.y的“无限”。
B:在短时间后重新询问插入位置的文本视图。我检查了一些延迟值; 0.05似乎足够了。
代码:
- (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 ...
}
答案 1 :(得分:0)
所以,你是对的。
你必须使用:
- (void)textViewDidChangeSelection:(UITextView *)textView
我会把它称为最后一个。在此之后,您将获得目前的插入符号位置。