1

I am using this code to rotate a view 360 degrees infinitely. But my view is not rotating:

func rotateImageView() {

        UIView.animate(withDuration: 3.0, delay: 0, options: [.repeat, .curveLinear], animations: {
            self.vinylView.transform = CGAffineTransform(rotationAngle: .pi * 2)
        })
        
    }

How to fix it?

User
  • 121
  • 1
  • 2
  • 11
  • 1
    Does this answer your question? [UIView Infinite 360 degree rotation animation?](https://stackoverflow.com/questions/9844925/uiview-infinite-360-degree-rotation-animation) – Adis Sep 14 '20 at 08:56
  • UIView.animate will "look" at the final form of your image / view to determine how to animate it, so when you transform the image by .pi * 2, UIView.animate found no different hence seems do nothing. You could try separating the animation into few part and call them one by one. – paky Sep 14 '20 at 09:18

2 Answers2

2

Substitute pi * with /, delete repeat, add completion and recall the function like this:

private func rotateImageView() {
    UIView.animate(withDuration: 3, delay: 0, options: .curveLinear, animations: {
        self.vinylView.transform = self.vinylView.transform.rotated(by: .pi / 2)
    }) { (finished) in
        if finished {
            self.rotateImageView()
        }
    }
}
Fabio
  • 5,432
  • 4
  • 22
  • 24
1

Solution using CABasicAnimation

// Rotate vinvlView
vinylView.layer.add(CABasicAnimation.rotation, forKey: nil)

extension CABasicAnimation {
    static let rotation : CABasicAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        animation.repeatCount = .infinity // Rotate a view 360 degrees infinitely
        animation.fromValue = 0
        animation.toValue = CGFloat.pi * 2
        animation.duration = 3.0
        return animation
    }()
}
Cruz
  • 2,602
  • 19
  • 29