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

你。 提交于 2019-11-30 11:10:56

The completion block will only get called when the animation is interrupted. For example it gets called when the app goes in the background and comes back to the foreground again (via multitasking). In that case the animation is stopped. You should restart the animation when that happens.

To stop the animation you can remove it from the view's layer:

[button.layer removeAllAnimations];

Old but another option.

You can also setup another animation which is not repeating on the same view, that way you can also capture it in the current state and return it to how it is by using the option UIViewAnimationOptionBeginFromCurrentState. Your completion block is also called.

-(void)someEventSoStop
{
    button.transform = CGAffineTransformMakeScale(1.0, 1.0);
    [UIView animateWithDuration: 0.4
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
                     animations: ^{
                         button.transform = CGAffineTransformIdentity;
                     } completion: ^(BOOL finished){

                     }];
}

I've solved the problem by calling [button.layer removeAllAnimations].

As per the documentation of View class reference: If you used any of the class methods such as animateWithDuration:delay:options:animations:completion: if the duration is set to negative value or 0, the changes are made without performing animation. so I did something like this to stop the infinite animation:

[UIView animateWithDuration:0.0 animations:^{
      button.layer.affineTransform = CGAffineTransformIdentity;
  }];

I think this is better than removing all animations from the layer as in the suggested answer. Note that this is applicable for all other class animation methods in the UIView class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!