animate rotation UIImageView in swift

======= Extension for UIView =======

I found this answer from the Internet, and I test it, working perfectly fine. Hope this will help to any one, just change the UIView to your need such as, UIView, UIButton, UIImageView, etc. and access with the myUIView.rotate() function, here myUIView should be replace with your View name (IBOutlet -> name) with correct view type for extension. This is the link that I found this answer. And this method is easy and working!

=== SWIFT 3 / 4 ===

extension UIView{
    func rotate() {
        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.toValue = NSNumber(double: M_PI * 2)
        rotation.duration = 1
        rotation.cumulative = true
        rotation.repeatCount = FLT_MAX
        self.layer.addAnimation(rotation, forKey: "rotationAnimation")
    }
}

suggested improvements. Thanks for all suggestions.

=== SWIFT 5 ===

extension UIView{
    func rotate() {
        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.toValue = NSNumber(value: Double.pi * 2)
        rotation.duration = 1
        rotation.isCumulative = true
        rotation.repeatCount = Float.greatestFiniteMagnitude
        self.layer.add(rotation, forKey: "rotationAnimation")
    }
}

And then call that extension like follow:

self.your_UIViewOutletName_myUIView_here.rotate()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)