【问题标题】:How can I set UITextView selectedTextRange with animation and scroll position如何使用动画和滚动位置设置 UITextView selectedTextRange
【发布时间】:2017-07-20 13:29:48
【问题描述】:

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

但是,制作动画并不是那么容易。我找不到setSelectedTextRange(animated:)。将其设置在 UIView.animate... 块内似乎没有任何作用。我能想到的最好的方法是手动为滚动设置动画,然后在完成集中设置selectedTextRange。然而,这很脆弱,通常看起来波涛汹涌,有时似乎根本不起作用。

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

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

【问题讨论】:

    标签: ios swift animation uitextview


    【解决方案1】:

    您可以使用 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 添加到您的视图控制器并设置 textView 委托:

    textView.delegate = self
    

    【讨论】:

    • 使用scrollViewDidEndScrollingAnimation(scrollView:) 比等待完成块要好一点,因为我不必担心动画有多长。但我想要一些更干净的东西,在制作动画时不会将光标留在顶部。
    • 我看不出光标出现在动画之后而不是在动画期间有什么关系。我认为您不希望您的用户在动画进行时打字?因此,您实际上应该在动画进行时禁用光标。 @RyanPoolos
    • @RyanPoolos 如果这对您有帮助,请接受答案
    猜你喜欢
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多