iosswiftcakeyframeanimation

Reverse the rotation of UIImageView using CAKeyframeAnimation


I'm using the following code to rotate an image infinitely, the rotation is clockwise but I also need it to reverse rotation to counter clockwise every 1-2 rotations and then back to clockwise, how to get this to work?

    /// Image Rotation - CAKeyframeAnimation
func rotate(imageView: UIImageView, rotationSpeed: Double) {

    let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")

    animation.duration = rotationSpeed
    animation.fillMode = CAMediaTimingFillMode.forwards
    animation.repeatCount = .infinity
    animation.values = [0, Double.pi/2, Double.pi, Double.pi*3/2, Double.pi*2]

    /// Percentage of each key frame
    let moments = [NSNumber(value: 0.0), NSNumber(value: 0.1),
                   NSNumber(value: 0.3), NSNumber(value: 0.8), NSNumber(value: 1.0)]
    animation.keyTimes = moments

    imageView.layer.add(animation, forKey: "rotate")
}

Solution

  • Set animation.autoreverses = true, will reverse an animation.