IOS stop animationWithDuration to complete

I have a CollectionView and I want to create an animation inside the CollectionViewCell selected by the user. I decided to use animateKeyframesWithDuration because I want to create a custom animation step by step. My code is as follows:

func animate() { UIView.animateKeyframesWithDuration(1.0, delay: 0.0, options: .AllowUserInteraction, animations: { () -> Void in UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: { () -> Void in // First step }) UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: { () -> Void in // Second step }) }) { (finished: Bool) -> Void in if self.shouldStopAnimating { self.loadingView.layer.removeAllAnimations() } else { self.animate() } } } 

Runs inside a custom CollectionViewCell when it is selected. The problem is that I want to force the animation to stop right away at some specific point. But when I do this, the animation does not stop completely, it just moves the remaining animation to another cell (perhaps the last reused cell?)

I do not understand why this is happening. I tried different approaches, but none of them could successfully stop the animation before entering the completion block normally

Does anyone have an idea about this?

+5
source share
1 answer

Instead of removing the animation from the layer, you can try adding another animation with a very short duration, which sets the view properties that you want the animation to stop.

Something like that:

 if self.shouldStopAnimating { UIView.animate(withDuration: 0.01, delay: 0.0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { () -> Void in //set any relevant properties on self.loadingView or anything else you're animating //you can either set them to the final animation values //or set them as they currently are to cancel the animation }) { (completed) -> Void in } } 

This answer may also be helpful.

0
source

Source: https://habr.com/ru/post/1245662/


All Articles