如何设置带有动画和滚动位置的UITextView selectedTextRange [英] How can I set UITextView selectedTextRange with animation and scroll position
问题描述
我一直在尝试找到一种将光标设置在带有动画的长UITextView底部的方法。设置起来并不太困难,实际上这个答案很好地覆盖了它。 https://stackoverflow.com/a/34922332/563381
I've been trying to figure out a way to set the cursor to the bottom of a long UITextView with animation. Setting it wasn't too difficult, in fact this answer covers it very well. https://stackoverflow.com/a/34922332/563381
但是,对其进行动画处理并非易事。我找不到一个 setSelectedTextRange(animated:)
。将其设置在 UIView.animate ...
块内似乎没有任何作用。我能想到的最好的方法是手动对滚动进行动画处理,然后在完成时设置 selectedTextRange
。但这很脆弱,通常看起来很杂乱,有时似乎根本不起作用。
However, animating it isn't so easy. There isn't a setSelectedTextRange(animated:)
that I can find. Setting it inside a UIView.animate...
block doesn't seem to do anything. The best I've been able to come up with is to animate the scroll manually then in the completion set the selectedTextRange
. However this is fragile, often looks choppy, and seems on occasion to not work at all.
设置 selectedTextRange
它确实跳到了该位置。如果有一种方法可以避免这种跳跃,则动画可能会更流畅,并且至少不会那么脆弱,因为它不需要延迟,您可以使用 setContentOffset(animated)
无需等待设置 selectedTextRange
。
When you set selectedTextRange
it does jump to that location. If there was a way to avoid that jump the animation might be smoother and at least would be less fragile since it wouldn't require a delay and you could use setContentOffset(animated)
without needing to wait to set the selectedTextRange
.
另一种选择是找到一种导致 selectedTextRange
跳转为动画本身。在此方面,我尝试了在之前禁用滚动并在之后重新启用滚动的技巧,但这似乎对我不起作用。猜测在更高版本的iOS中已更改。
The other option is to find a way to cause the selectedTextRange
jump to be animated itself. On this front I tried the trick of disabling scrolling before and reenabling after but that didn't seem to work for me. Guessing that has changed in later versions of iOS.
推荐答案
您可以使用setContentOffset(_,animation :)并检测结束动画并使用scrollViewDidEndScrollingAnimation并设置光标,如下所示:
You can use setContentOffset(_, animated:) and detect the end of the animation with scrollViewDidEndScrollingAnimation and set the cursor like so:
// 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添加到视图控制器并设置textView委托:
You will need to add UITextViewDelegate to your view controller and set the textView delegate:
textView.delegate = self
这篇关于如何设置带有动画和滚动位置的UITextView selectedTextRange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!