首页 > 如何准确获取 UITextView 的光标位置?

如何准确获取 UITextView 的光标位置?

需求是在用户开始输入的时候,获取 UITextView 的光标位置。

我用的是CGFloat cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin.y;现在问题是,写在哪个函数里能正确获取到textView.selectedTextRange

我发现写在- (void)textViewDidBeginEditing:(UITextView *)textView里是不行的,它每次取到的是上一次取的位置。比如用户先点第2行,它返回第2行;收起键盘之后,再点第1行,它返回还是第2行;收起键盘之后再点第3行,它返回是第1行……

而写在- (void)textViewDidChangeSelection:(UITextView *)textView取到的是正确的。问题在于,如果用户点的还是上次点的那行,就不会触发这个回调了。比如用户先点第2行,收起键盘之后又点第2行,并不会触发textViewDidChangeSelection这个函数。

请问有什么解决方法吗?谢谢~


最后我是这样做的:

- (void)textViewDidBeginEditing:(UITextView *)textView {
    [self performSelector:@selector(textViewDidChange:) withObject:textView afterDelay:0.1f];
}

- (void)textViewDidChange:(UITextView *)textView {
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
    
    CGFloat cursorPosition;
    if (textView.selectedTextRange) {
        cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin.y;
    } else {
        cursorPosition = 0;
    }
    CGRect cursorRowFrame = CGRectMake(0, cursorPosition, kScreenWidth, kMinTextViewHeight);
    CGRect textViewFrame = [self.tableView convertRect:cursorRowFrame fromView:textView];
    
    [self.tableView scrollRectToVisible:textViewFrame animated:YES];
}

其中的beginUpdatesendUpdates是我其他需求要用的。核心意思就是在textViewDidBeginEditing里延时调用一个函数,只要延0.1s,之后再获取光标就正常了……

【热门文章】
【热门文章】