ios - 如何设置带有动画和滚动位置的 UITextView selectedTextRange

标签 ios swift animation uitextview

我一直在想办法将光标设置到带有动画的长 UITextView 的底部。设置它并不太困难,事实上这个答案很好地涵盖了它。 https://stackoverflow.com/a/34922332/563381

但是,制作动画并不那么容易。我找不到 setSelectedTextRange(animated:)。将它设置在 UIView.animate... block 中似乎没有任何作用。我能想到的最好办法是手动设置滚动动画,然后在完成时设置 selectedTextRange。然而,这是脆弱的,经常看起来不稳定,有时似乎根本不起作用。

当您设置 selectedTextRange 时,它会跳转到该位置。如果有办法避免这种跳跃,动画可能会更流畅,至少不会那么脆弱,因为它不需要延迟,您可以使用 setContentOffset(animated) 而无需等待设置selectedTextRange

另一种选择是找到一种方法使 selectedTextRange 跳转本身具有动画效果。在这方面,我尝试了在之前禁用滚动并在之后重新启用滚动的技巧,但这似乎对我不起作用。猜测在更高版本的 iOS 中已经改变。

最佳答案

您可以使用 setContentOffset(_, animated:) 并使用 scrollViewDidEndScrollingAnimation 检测动画的结束并像这样设置光标:

// The action to scroll down
@IBAction func test(_ sender: Any) {

    let offset = self.textView.contentSize.height - self.textView.frame.height
    self.textView.setContentOffset(CGPoint(x: 0, y: offset), animated: true)
}

// Setting the cursor down
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {

    let offset = self.textView.contentSize.height - self.textView.frame.height

    if scrollView.contentOffset == CGPoint(x: 0, y: offset) {
        let newPosition = textView.endOfDocument
        self.textView.selectedTextRange = self.textView.textRange(from: newPosition, to: newPosition)
    }
}

您需要将 UITextViewDelegate 添加到您的 View Controller 并设置 textView 委托(delegate):

textView.delegate = self

关于ios - 如何设置带有动画和滚动位置的 UITextView selectedTextRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45216232/

相关文章:

iphone - Stock 应用程序中使用的 iOS 日期 slider /选择器

ios - 如何快速设置选项卡栏 Controller 的默认选项卡

javascript - 我的平滑滚动 js 不会触发动画?

css - 如何让这个设计响应?

ios - 大小类问题

ios - NSTimer 不调用选择器中的方法

ios - shouldReinviteDisconnectedPlayer 在 iOS 10.3 中未被调用

ios - 如何自动将用户分为不同的组(身份池)?

ios - 无法在 swift 中使用 Objective-c block

javascript - 通过 Javascript 更改 Webkit 属性?