iOS stop animateWithDuration before completion
Asked Answered
T

1

7

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?

Trainor answered 23/3, 2016 at 20:44 Comment(1)
did you find a solution for this?Trilobate
B
0

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.

Brashear answered 23/3, 2016 at 23:42 Comment(1)
It still doesn't work. On my selected cell the animation stops as normal. The real problem is that it continues on another cell. I have also tried with UIView.setAnimationsEnabled(false) but in vain. This is really annoyingTrainor

© 2022 - 2024 — McMap. All rights reserved.