There are various ways to perform 360-degree animation with a UIView.
Using CABasicAnimation
var rotationAnimation = CABasicAnimation() rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z") rotationAnimation.toValue = NSNumber(value: (Double.pi * 2.0)) rotationAnimation.duration = 1.0 rotationAnimation.isCumulative = true rotationAnimation.repeatCount = 100.0 view.layer.add(rotationAnimation, forKey: "rotationAnimation")
Here are the extension functions for UIView that handle rotation start and stop operations:
extension UIView { // Start rotation func startRotation() { let rotation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.fromValue = 0 rotation.toValue = NSNumber(value: Double.pi * 2) rotation.duration = 1.0 rotation.isCumulative = true rotation.repeatCount = FLT_MAX self.layer.add(rotation, forKey: "rotationAnimation") } // Stop rotation func stopRotation() { self.layer.removeAnimation(forKey: "rotationAnimation") } }
Now, using the closure of UIView.animation :
UIView.animate(withDuration: 0.5, animations: { view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) }) { (isAnimationComplete) in UIView.animate(withDuration: 0.5) { view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) } }
source share