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

kbp*_*ius 6 ios swift2

我找遍了SO一个简单的解决方案来获得光标的当前位置,然后滚动到它(假设键盘可见的).在某些情况下,大多数人似乎过于复杂和/或无效.如果光标位于键盘下方,我怎样才能每次都进行滚动工作?

kbp*_*ius 8

1)确保你UITextViewcontentInset设置正确,并且你textView已经firstResponder做好了.该contentInset属性告诉textView用户可见区域的位置.如果键盘可见,请确保该textView.contentInset.bottom属性已设置为键盘的顶部边框,否则textView可能会滚动到键盘后面不可见的空间.

有关更多信息,请参阅此SO帖子:什么是UIScrollView contentInset属性?

2)在我的插图准备好之后,并且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)
    }
 }
Run Code Online (Sandbox Code Playgroud)

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

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

额外信息:要将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.
Run Code Online (Sandbox Code Playgroud)