3

Possible Duplicate:
Cancel a UIView animation?

I have the following animation and i want to stop it when i press a button. Can you please tell me how can i do it? I can't figure it out how. Thanks.

-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void    *)context 
{
[UIView beginAnimations:@"Move randomly" context:nil]; 
[UIView setAnimationDuration:1]; 
// [UIView setAnimationBeginsFromCurrentState:NO];


CGFloat x = (CGFloat) (arc4random() % (int) self.bounds.size.width); 
CGFloat y = (CGFloat) (arc4random() % (int) self.bounds.size.height); 

CGPoint squarePostion = CGPointMake(x, y); 
strechView.center = squarePostion; 

[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];

[UIView commitAnimations];

} 
Community
  • 1
  • 1
alexclp
  • 191
  • 1
  • 1
  • 9

4 Answers4

6

Try this:

[myView.layer removeAllAnimations];

and be sure to import the Quartz framework as well:

#import <QuartzCore/QuartzCore.h>

Animations are applied using CoreAnimation in the QuartzCore framework, even the UIView animation methods. Just target the view's layer that you want to stop animating, and remove its animations.

gdavis
  • 2,556
  • 1
  • 20
  • 25
3

You could do this:

[self.view.layer removeAnimationForKey:@"Move randomly"];

This is more effective than calling [self.view.layer removeAllAnimations] because this can potentially remove other animations that you would want to keep.

pasawaya
  • 11,515
  • 7
  • 53
  • 92
0

You can just change the object/property that currently animated. It will stop animation.

folex
  • 5,122
  • 1
  • 28
  • 48
0

I suggest you use NSTimer.

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(yourAnimation) userInfo:nil repeats:YES];

- (void)responseToButton:(UIButton *) _button {
    //when you want to stop the animation
    [myTimer invalidate];
}

- (void)yourAnimation {
      // move the view to a random point
}

Besides, you can set the NSTimer works on another thread so that the main thread can response when you press even your TimeInterval value is very small

TedCheng
  • 655
  • 4
  • 11