I\'m trying to animate a rotation of 180 degrees of a UIImageView
in Swift
UIView.animateWithDuration(1.0, animations: { () -> Void in
Swift 5.0
extension UIImageView{
func rotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = NSNumber(value: Double.pi * 2)
rotation.duration = 2
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
self.layer.add(rotation, forKey: "rotationAnimation")
}
}
Updating to @Rakshitha Muranga Rodrigo answer.
Be sure to be in the Main thread
DispatchQueue.main.async {
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
}) { (succeed) -> Void in
}
}
You left out the / 180
on CGFloat(180 * M_PI)
. Try:
UIView.animate(withDuration: 1.0) {[weak self] in
self?.arrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
}
======= 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()