如何在UITextView中滚动到当前光标位置?

9
我在S.O.上搜寻了很久,想找到一个简单的解决方案来获取光标的当前位置,然后滚动到该位置(假设键盘是可见的)。大多数方法似乎都过于复杂,并且在某些情况下效果不佳。我该如何使滚动功能始终正常工作,无论光标是否在键盘下方?
1个回答

11

1)确保你的UITextViewcontentInset已正确设置,并且在执行此操作之前,textView已经是firstRespondercontentInset属性告诉textView哪里是用户可见区域。如果键盘可见,请确保将textView.contentInset.bottom属性设置为键盘顶部边框,否则textView可能会滚动到不可见的空间(即键盘后面)。

请参阅此S.O.帖子以获取更多信息:UIScrollView contentInset属性是用来做什么的?

2)在我的textView准备好了插图并成为firstResponder之后,我调用以下函数:

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当前为firstResponder并且contentInset已经在此之前正确设置),只需调用:

[self.textView scrollRangeToVisible:self.textView.selectedRange];

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接