gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:44:09 30 4
gpt4 key购买 nike

我正在努力将键盘滚动到 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 时结果相同

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

最佳答案

在将 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")
}
}
}

关于swift - 将 ScrollView/Keyboard 移动到 UITextView 光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549771/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com