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

481 views Asked by At

My code below is a button that when hit applies animation. Right now there are two animations. I would like to do a sequence the animations meaning have the 2nd animation not start until the first animation has completed.

    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)
       }}
2

There are 2 answers

0
AudioBubble On BEST ANSWER

The easiest way of doing that would be using the completion block of the animate(withDuration:animations:completion:) method. The completion block is executed when the animation sequence ends. In your case, it would look like this :

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)


     })
})
0
Vitaliy A On

There is also convenient way to make sequence of concurrent animations by using 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
            })