gpt4 book ai didi

ios - 如何滚动到 UITextView 中的当前光标位置?

转载 作者:可可西里 更新时间:2023-11-01 03:45:30 25 4
gpt4 key购买 nike

我搜索了整个 S.O.获取光标当前位置的简单解决方案,然后滚动到它(假设键盘可见)。在某些情况下,大多数看起来过于复杂和/或无效。无论光标是否在键盘下方,我怎样才能使滚动每次都有效?

最佳答案

1) 确保您的 UITextViewcontentInset 设置正确并且您的 textView 已经是 firstResponder在这样做之前。 contentInset 属性告诉 textView 用户可见区域的位置。如果键盘可见,请确保 textView.contentInset.bottom 属性已设置为键盘的上边框,否则 textView 可能会滚动到不可见的空间,在键盘后面。

查看此 S.O.发布更多信息:What's the UIScrollView contentInset property for?

2) 在我的 insets 准备就绪后,textViewfirstResponder,我调用以下函数:

private func scrollToCursorPositionIfBelowKeyboard() {
let caret = textView.caretRectForPosition(textView.selectedTextRange!.start)
let keyboardTopBorder = textView.bounds.size.height - keyboardHeight!

// Remember, the y-scale starts in the upper-left hand corner at "0", then gets
// larger as you go down the screen from top-to-bottom. Therefore, the caret.origin.y
// being larger than keyboardTopBorder indicates that the caret sits below the
// keyboardTopBorder, and the textView needs to scroll to the position.
if caret.origin.y > keyboardTopBorder {
textView.scrollRectToVisible(caret, animated: true)
}
}

可选:如果您只想滚动到光标的当前位置(假设 textView 当前是 firstRespondercontentInset 之前已经正确设置),只需调用:

private func scrollToCursorPosition() {
let caret = textView.caretRectForPosition(textView.selectedTextRange!.start)
textView.scrollRectToVisible(caret, animated: true)
}

额外信息:为了将 textView 滚动条设置为适当的高度,请通过执行以下操作修改 scrollIndicatorInsets:

// This is not relative to the coordinate plane. You simply set the `.bottom` property 
// as if it were a normal height property. The textView does the rest for you.
textView.contentInset.bottom = keyboardHeight
textView.scrollIndicatorInsets = textView.contentInset // Matches textView's visible space.

关于ios - 如何滚动到 UITextView 中的当前光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31864261/

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