Repeat an animation a variable number of times

后端 未结 4 1133

I was wondering how I can set an animation to repeat. The number of repetitions needs to be determined by a variable. In the following code, the variable int newPage

4条回答
  •  滥情空心
    2021-02-19 10:02

    To avoid the hiccup between animations, use keyframes. I wrote an extension that works on anything conforming to UIView (which is a ton of visual elements)

    Swift 4:

    import UIKit
    extension UIView{
        func rotate(count: Float, _ complete: @escaping ()->()) {
            UIView.animateKeyframes(withDuration: 1.0, delay: 0, options: [.repeat], animations: {
                //to rotate infinitely, comment the next line
                UIView.setAnimationRepeatCount(count)
                //rotate the object to 180 degrees
                UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5/1.0, animations: {
                    self.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)))
                })
                UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5/1.0, animations: {
                    //rotate the object from 180 to 360 degrees
                    self.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi * 2)))
                })
            }, completion:{ _ in
                complete()
            })
        }
    }
    

    To call it anywhere in the app:

    view.rotate() { /*do after*/ }
    

提交回复
热议问题