4

I have an animation that needs to be repeated until I decided to stop it.

How can I stop in animation after a button click?

[UIView animateWithDuration:0.2 delay:0 options:(UIViewAnimationCurveLinear | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat) animations:^{

        CGAffineTransform transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(5));
        self.transform = transform;

    }  completion:^(BOOL finished){

    }];
Charles
  • 50,943
  • 13
  • 104
  • 142
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • 3
    possible duplicate of [How to have a handler to repeat UIView animateWithDuration?](http://stackoverflow.com/questions/6766955/how-to-have-a-handler-to-repeat-uiview-animatewithduration) – sch Mar 18 '12 at 00:07

2 Answers2

13

You have to add one other option UIViewAnimationOptionAllowUserInteraction ...

You should try this:

[UIView animateWithDuration:2 delay:0 options:UIViewAnimationCurveLinear | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | 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];
Nirav Gadhiya
  • 6,342
  • 2
  • 37
  • 76
  • 1
    Good response on the concrete question, without suggesting another approach to animate view. Good job. – SSemashko Jan 17 '14 at 07:58
2

U can make use of CABasicAnimation instead.

    CABasicAnimation *appDeleteShakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
appDeleteShakeAnimation.autoreverses = YES;
appDeleteShakeAnimation.repeatDuration = HUGE_VALF;
appDeleteShakeAnimation.duration = 0.2;
appDeleteShakeAnimation.fromValue = [NSNumber numberWithFloat:-degreeToRadian(5)];
appDeleteShakeAnimation.toValue=[NSNumber numberWithFloat:degreeToRadian(5)];
[self.layer addAnimation:appDeleteShakeAnimation forKey:@"appDeleteShakeAnimation"];

Then when u want to stop it you can just call

[self.layer removeAnimationForKey:@"appDeleteShakeAnimation"];
Raj
  • 1,091
  • 1
  • 9
  • 18