将ScrollView /键盘移动到UITextView光标位置

问题描述 投票:0回答:1

我正在将键盘滚动到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

swift scrollview uitextview cursor-position
1个回答
0
投票

直到将调度队列放在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")
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.