How can I repeat chained animation in Swift?

Viewed 192

I would like to animate the whole chain for forever.

UIView.animate(withDuration: 2.0, delay: 0.2, options: .curveEaseOut, animations: {
        self.circleImageView.transform = CGAffineTransform(scaleX: 9, y: 9)
    }) { (_) in
        UIView.animate(withDuration: 2.0, delay: 0.2, options: .curveEaseIn, animations: {
            self.circleImageView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        }, completion: nil)
    }
2 Answers

You can wrap the two animations within a keyframe animation. Then you can .repeat that:

UIView.animateKeyframes(withDuration: 4.4, delay: 0, options: .repeat, animations: { 
    UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 2.0/4.4) { 
        self.circleImageView.transform = .init(scaleX: 9, y: 9)
    }
    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 2.0/4.4) { 
        self.circleImageView.transform = .init(scaleX: 0.01, y: 0.01)
    }
})

Wrap it up inside a method:

func repeatingAnimation() {
    UIView.animate(withDuration: 2.0, delay: 0.2, options: .curveEaseOut, animations: {
        self.circleImageView.transform = CGAffineTransform(scaleX: 9, y: 9)
    }) { (_) in
        UIView.animate(withDuration: 2.0, delay: 0.2, options: .curveEaseIn, animations: {
            self.circleImageView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        }, completion: { [weak self] _ in
            self?.repeatingAnimation()
        })
    }
}
Related