razvan
razvan

Reputation: 133

iOS stop animateWithDuration before completion

I have a CollectionView and I want to create an animation inside the CollectionViewCell selected by the user. I chose to use animateKeyframesWithDuration because I want to create a custom animation step by step. My code looks like this:

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()
            }
        }
}

This is executed inside the custom CollectionViewCell when it is selected. The problem is that I want to force stop the animation immediately at some certain point. But when I do that, the animation doesn't fully stop, it just moves the remaining animation on a different cell (probably the last reused cell?)

I can't understand why this is happening. I have tried different approaches but none of them successfully stop the animation before normally entering the completion block

Does anyone have any idea about this?

Upvotes: 7

Views: 1372

Answers (1)

Chance Hudson
Chance Hudson

Reputation: 2859

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

Something like this:

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.

Upvotes: 0

Related Questions