1

I want to spin a imageview for forever. I tried following code:

    UIView.animateWithDuration(3, animations: {
        self.loginLogo.transform = CGAffineTransformMakeRotation((360 * CGFloat(M_PI)) / 360)
        }){ (finished) -> Void in
            self.rotateImage()
    }

But this is working for one time. My imageview is not spinning forever. How can I fix it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73

3 Answers3

1

If you want to rotate your image forever you can do it this way:

func rotateViewLayer() {
    let rotateView = CABasicAnimation()

    rotateView.fromValue = 0.degreesToRadian
    rotateView.toValue = 360.degreesToRadian
    rotateView.duration = 1
    rotateView.repeatCount = Float.infinity
    rotateView.removedOnCompletion = false
    rotateView.fillMode = kCAFillModeForwards
    rotateView.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    imageView.layer.addAnimation(rotateView, forKey: "transform.rotation.z")
}

And here is your helper extension:

extension Int {
    var degreesToRadian : CGFloat {
        return CGFloat(self) * CGFloat(M_PI) / 180.0
    }
}

And you can refer THIS sample project for more Info.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0

use this on layer of your view

var myImageView:UIImageView?
    var rotation = CABasicAnimation(keyPath: "transform.rotation")
    rotation.fromValue = 0.0
    rotation.toValue = 2*M_PI
    rotation.duration = 1.1
    rotation.repeatCount = Float.infinity
    myImageView?.layer.addAnimation(rotation, forKey: "Spin")
Ankit Sachan
  • 7,690
  • 16
  • 63
  • 98
0

This should work

func startAnimationWithDuration(duration:CGFloat)
    {
        var rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.fromValue = 0
        rotationAnimation.toValue = 2 * M_PI
        rotationAnimation.duration = NSTimeInterval(duration)
        rotationAnimation.repeatCount = 1000.0 //some large value
        imageView.layer.addAnimation(rotationAnimation, forKey: "spin")
    }
ImAshwyn
  • 26
  • 4