【问题标题】:Moving ScrollView/Keyboard to UITextView cursor position将 ScrollView/Keyboard 移动到 UITextView 光标位置
【发布时间】:2019-04-06 13:56:29
【问题描述】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多