I'm trying to animate a rotation of 180 degrees of a UIImageView
in Swift
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
}) { (succeed) -> Void in
}
But isnt animating at all.
I want to use animateWithDuration cause i want to make it back at some point using CGAffineTransformMakeIdentity
Using UIView
animations works.
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn)
let radians = CGFloat(180 * M_PI / 180)
arrowImageView.transform = CGAffineTransformMakeRotation(radians)
UIView.commitAnimations()
======= 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()
Here is code to rotate imageview. swift 3.0
UIView.animate(withDuration:2.0, animations: {
self.dropDownImage.transform = CGAffineTransform(rotationAngle: CGFloat(imageRotation))
})
Updated swift 4.0 version:
let rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = Double.pi * 2
rotation.duration = 0.25 // or however long you want ...
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
yourView.layer.add(rotation, forKey: "rotationAnimation")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With