How to cancel UIViews block-based animation?

喜夏-厌秋 提交于 2019-11-29 01:16:13

If you start a new animation that takes 0.0 seconds and goes to the state you want to go to, it will cancel the old one and start the new (instant) 'animation'.

Example for when you want to stop a moving view by going to the place it already is at:

[UIView animateWithDuration:0.0
                      delay:0.0
                    options:UIViewAnimationOptionBeginFromCurrentState
                 animations:^{movingView.frame = ((CALayer *)movingView.layer.presentationLayer).frame;}
                 completion:^(BOOL finished){}
 ];

options:UIViewAnimationOptionBeginFromCurrentState is important. Not calling it will let your animation start at the end state of the previous animation. In movement, it would warp to the end location before warping to the place you want it to stop at. Even though your cancel-'animation' is instant, the jumping back and forth may be visible.

Note: The animation time doesn't have to be 0.0 seconds, any animation will cancel the old one. Not entirely sure about different types of animations though. For example, I don't know if changing a frame would stop a fade.

You can remove all the animations from the views layer

[movingView.layer removeAllAnimations];

Blocks will always complete after they start, and cannot be stopped (unless you crash the app). You might want to use notification center or NSTimer to manually change frames instead.

Setting animation options UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction work for me.

Use it like this:

[UIView animateWithDuration:0.5
                          delay:0.0
         usingSpringWithDamping:0.7
          initialSpringVelocity:0
                        options:UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                    // Do your stuff here, like changing the frame etc.
                    self.containerView.frame = CGRectMake(0, 100, 300, 300);
    } completion:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!