I\'m trying to animate a rotation of 180 degrees of a UIImageView
in Swift
UIView.animateWithDuration(1.0, animations: { () -> Void in
======= 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()