移动 ScrollView/Keyboard 到 UITextView 光标位置

Moving ScrollView/Keyboard to UITextView cursor position

我正在努力将键盘滚动到 UITextView 中光标的当前位置。

我是这样使用 textViewDidChange 的:

func textViewDidChange(_ textView: UITextView) {
        if let cursorPosition = textView.selectedTextRange?.end {

            let caretPositionRect = textView.caretRect(for: cursorPosition)
            print(caretPositionRect, "caret")
            DispatchQueue.main.async{ [weak self] in
                let pointsuperview = textView.convert(caretPositionRect, to: self?.vc?.mainView.scrollView)
                self?.vc?.mainView.scrollView.scrollRectToVisible(pointsuperview, animated: false)
                print(pointsuperview, "ps")
            }
        }
    }

只要有角色或者我要回去,它就有效。但是,如果我通过在最后一行按回车键来添加新行,我会得到如下输出:

(inf, inf, 0.0, 0.0) caret

当我使用退格键时,我再次获得有效值。

有效值如下所示:

(4.0, 7.0, 2.0, 21.5) caret

使用 selectedTextRange.start 时结果相同

我尝试了这个问题的解决方案:

我遇到了同样的问题,直到我将 Dispatch Queue 放在 textview.caretRect(for:)

之前
func textViewDidChange(_ textView: UITextView) {
        if let cursorPosition = textView.selectedTextRange?.end {

            DispatchQueue.main.async{ [weak self] in
                let caretPositionRect = textView.caretRect(for: cursorPosition)
                print(caretPositionRect, "caret")
                let pointsuperview = textView.convert(caretPositionRect, to: self?.vc?.mainView.scrollView)
                self?.vc?.mainView.scrollView.scrollRectToVisible(pointsuperview, animated: false)
                print(pointsuperview, "ps")
            }
        }
    }

如果不起作用,请尝试添加 1 毫秒的延迟

func textViewDidChange(_ textView: UITextView) {
        if let cursorPosition = textView.selectedTextRange?.end {

        let deadlineTime = DispatchTime.now() + .milliseconds(1)
        DispatchQueue.main.asyncAfter(deadline: deadlineTime) { [weak self] in
                let caretPositionRect = textView.caretRect(for: cursorPosition)
                print(caretPositionRect, "caret")
                let pointsuperview = textView.convert(caretPositionRect, to: self?.vc?.mainView.scrollView)
                self?.vc?.mainView.scrollView.scrollRectToVisible(pointsuperview, animated: false)
                print(pointsuperview, "ps")
            }
        }
    }