I have animation
func startRotate360() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = Double.pi * 2
rotation.duration = 1
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
self.layer.add(rotation, forKey: "rotationAnimation")
}
What I want is ability to stop animation by setting its repeat count to 1, so it completes current rotation (simply remove animation is not ok because it looks not good)
I try following
func stopRotate360() {
self.layer.animation(forKey: "rotationAnimation")?.repeatCount = 1
}
But I get crash and in console
attempting to modify read-only animation
How to access writable properties ?
Give this a go. You can in fact change CAAnimations that are in progress. There are so many ways. This is the fastest/simplest. You could even stop the animation completely and resume it without the user even noticing.
You can see the start animation function along with the stop. The start animation looks similar to yours while the stop grabs the current rotation from the presentation layer and creates an animation to rotate until complete. I also smoothed out the duration to be a percentage of the time needed to complete based on current rotation z to full rotation based on the running animation. Then I remove the animation with the repeat count and add the new animation. You can see the view rotate smoothly to the final position and stop. You will get the idea. Drop it in and run it and see what you think. Hit the button to start and hit it again to see it finish rotation and stop.
Result:
Maybe this is not the best solution but it works, as you say you can not modify properties of the
CABasicAnimation
once is created, also we need to remove therotation.repeatCount = Float.greatestFiniteMagnitude, if not
CAAnimationDelegatemethod
animationDidStop` is never called, with this approach the animation can be stoped without any problems as you needstep 1: first declare a variable flag to mark as you need stop animation in your custom class
step 2: add a method to stopAnimation after ends
step 3: add a method to get your custom animation
step 4: Modify your startRotate360 func to use your
getRotate360Animation()
methodstep 5: Implement
CAAnimationDelegate
in your classThis works and was tested
Hope this helps you