Swift 3:
Using CABasicAnimation
var rotationAnimation = CABasicAnimation() rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z") rotationAnimation.toValue = NSNumber(value: (Double.pi)) rotationAnimation.duration = 1.0 rotationAnimation.isCumulative = true rotationAnimation.repeatCount = 100.0 view.layer.add(rotationAnimation, forKey: "rotationAnimation")
The following are the extension functions for UIView that handle rotation start and stop operations:
extension UIView { func startRotation() { let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.fromValue = 0 rotation.toValue = NSNumber(value: Double.pi) rotation.duration = 1.0 rotation.isCumulative = true rotation.repeatCount = FLT_MAX self.layer.add(rotation, forKey: "rotationAnimation") } func stopRotation() { self.layer.removeAnimation(forKey: "rotationAnimation") } }
Now using the UIView.animation closure:
UIView.animate(withDuration: 0.5, animations: { button.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi))) }) { (isAnimationComplete) in
source share