如何在文本视图上制作序列动画 (swift3)

How to do a sequence animation on a textview (swift3)

我下面的代码是一个按钮,当点击时应用动画。现在有两个动画。我想做一个动画序列,意思是让第二个动画在第一个动画完成之前不开始。

    var speed: CGFloat = 5.3 // speed in seconds
@IBAction func press(_ sender: Any) {
    self.theTextView.resignFirstResponder()

    UIView.animate(withDuration: TimeInterval(speed), animations: {
            ////1st action[
               self.theTextView.contentOffset = .zero
               self.theTextView.setContentOffset(.zero, animated: true)]
      /////2nd action[
        self.theTextView.contentOffset = CGPoint(x: 0, y: self.theTextView.contentSize.height)]

    }, completion: nil)
       }}

最简单的方法是使用 animate(withDuration:animations:completion:) 方法的完成块。完成块在动画序列结束时执行。在您的情况下,它看起来像这样:

UIView.animate(withDuration: 6.0, animations: {

     // First animation goes here

     self.theTextView.contentOffset = CGPoint.zero

}, completion: { (finished) in

     // This completion block is called when the first animation is done.

     // Make sure the animation was not interrupted/cancelled :

     guard finished else {
        return
     }

     UIView.animate(withDuration: 1.0, animations: {

         // And the second animation goes here

        self.theTextView.contentOffset = CGPoint(x: 0, y: self.theTextView.contentSize.height)


     })
})

还有一种方便的方法可以使用 animateKeyframes:

制作并发动画序列
UIView.animateKeyframes(withDuration: 1, delay: 0, options: .calculationModeCubic, animations: {
                UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.3, animations: {
                    self.someView.alpha = 0.5
                    self.view.layoutIfNeeded()
                })
                //second animation
                UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.3, animations: {
                    self.someView.alpha = 1
                    self.view.layoutIfNeeded()
                })
            }, completion: { (finish) in
                // Do something on animation complete
            })