将ScrollView / Keyboard移动到UITextView光标位置

时间:2019-04-06 13:56:29

标签: swift scrollview 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")
            }
        }
    }

只要有角色或我要回去,它就可以工作。但是,如果我通过按Enter到最后一行来添加新行,则会得到如下输出:

  

(inf,inf,0.0,0.0)插入符

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

有效值如下:

  

(4.0,7.0,2.0,21.5)插入符

使用selectedTextRange.start时的结果相同

我尝试了以下问题的解决方案: Getting and Setting Cursor Position of UITextField and UITextView in Swift

1 个答案:

答案 0 :(得分:1)

在将调度队列放在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")
            }
        }
    }