Stop Repeating UIView Animation Block?

2019-07-15 14:24发布

问题:

I have a UIView animation block which uses the UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoReverse option so it keeps going, but at some points I need to stop the animation but more importantly stop it and have the view return to its original position.

I have tried [dot1.layer removeAllAnimations]; but that stops it in its tracks without returning it to its original position, it stops mid animation.

I have tried stopping it then just running a second animation to return it to its correct frame, but that can be a bit jerky as I don't know how far it needs to go with what duration etc.

So is it possible to simply have the animation stop after its completed its last cycle rather than mid way?

Thanks.

回答1:

You should try this:

[UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction animations:^
{
    view.frame = CGRectMake(0, 100, 200, 200);
} completion:^(BOOL finished)
{
    if(! finished) return;
}];

And to stop the animation use this:

[view.layer removeAllAnimations];


回答2:

I've tried the accepted solution and it didn't work for me. The animations just stopped after one run. Digging around on the net leads me to believe that [self.view.layer removeAllAnimations] is the recommended way to stop animations (another method can be seen in the following link as the asker's comment to the accepted solution

Stop an auto-reverse / infinite-repeat UIView animation with a BOOL / completion block).

The way that worked for me was the one given by BooRanger (even jrturton accepted it). I set a boolean property called stopAnimations in the class and initialise its value to NO. Whenever I want to stop the animations, I set stopAnimations to YES and then call [self.view.layer removeAllAnimations] in the next line. Then in the completion block, I do the following.

if(self.stopAnimations){
self.finishAnimations = NO;
return;
}

Hope this helps the someone. :)