Rotate a view for 360 degrees indefinitely in Swift? Rotate a view for 360 degrees indefinitely in Swift? ios ios

Rotate a view for 360 degrees indefinitely in Swift?


Swift 2.x way to rotate UIView indefinitely, compiled from earlier answers:

// Rotate <targetView> indefinitelyprivate func rotateView(targetView: UIView, duration: Double = 1.0) {    UIView.animateWithDuration(duration, delay: 0.0, options: .CurveLinear, animations: {        targetView.transform = CGAffineTransformRotate(targetView.transform, CGFloat(M_PI))    }) { finished in        self.rotateView(targetView, duration: duration)    }}

UPDATE Swift 3.x

// Rotate <targetView> indefinitelyprivate func rotateView(targetView: UIView, duration: Double = 1.0) {    UIView.animate(withDuration: duration, delay: 0.0, options: .curveLinear, animations: {        targetView.transform = targetView.transform.rotated(by: CGFloat(M_PI))    }) { finished in        self.rotateView(targetView: targetView, duration: duration)    }}


Swift 3.0

let imgViewRing = UIImageView(image: UIImage(named: "apple"))imgViewRing.frame = CGRect(x: 0, y: 0, width: UIImage(named: "apple")!.size.width, height: UIImage(named: "apple")!.size.height)imgViewRing.center = CGPoint(x: self.view.frame.size.width/2.0, y: self.view.frame.size.height/2.0)rotateAnimation(imageView: imgViewRing)self.view.addSubview(imgViewRing)

This is the animation logic

func rotateAnimation(imageView:UIImageView,duration: CFTimeInterval = 2.0) {        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")        rotateAnimation.fromValue = 0.0        rotateAnimation.toValue = CGFloat(.pi * 2.0)        rotateAnimation.duration = duration        rotateAnimation.repeatCount = .greatestFiniteMagnitude        imageView.layer.add(rotateAnimation, forKey: nil)    }

You can check output in this link


Use this extension to rotate UIImageView 360 degrees.

extension UIView {func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) {    let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")    rotateAnimation.fromValue = 0.0    rotateAnimation.toValue = CGFloat(M_PI)    rotateAnimation.duration = duration    if let delegate: CAAnimationDelegate = completionDelegate as! CAAnimationDelegate? {        rotateAnimation.delegate = delegate    }    self.layer.addAnimation(rotateAnimation, forKey: nil)}}

Than to rotate UIImageView simply use this method

self.YOUR_SUBVIEW.rotate360Degrees()