Yusuf OZKAN
Yusuf OZKAN

Reputation: 115

How do I loop UIAnimation?

I have an animation that plays fine. But at the end of the animation, the animation stops. I want the animation to loop. How can I do this? Here is my code:

    - (void) startTicker
{
    if (self.timerIsRunning) return;

    self.timerIsRunning = YES;

    NSTimer *newTimer = [NSTimer timerWithTimeInterval:(0.1) target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:newTimer forMode:NSDefaultRunLoopMode];

   [UIView beginAnimations:nil context:nil];
   [UIView setAnimationDuration:100.0];
   [UIView setAnimationDelegate:self];
   [UIView setAnimationDelay:0.0];
   [UIView setAnimationDidStopSelector:@selector(moveToLeft:finished:context:)];
   [UIView commitAnimations];


}


     -(void)moveToLeft:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context 
    { 

        imageView.left = 800; 
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:100.0];
        [UIView setAnimationDelay:0.0];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self cache:YES];
        imageView.right = 800;

        [UIView setAnimationDidStopSelector:@selector(moveToLeft2:finished2:context2:)];
        [UIView commitAnimations];



    }

Upvotes: 0

Views: 2960

Answers (1)

POF_Andrew_POF
POF_Andrew_POF

Reputation: 103

For loop animation the best way is to use block animations which are a part of UIView.

When calling the method:

+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion

The "option" you probably want is UIViewAnimationOptionAutoreverse and combined with the UIViewAnimationOptionRepeat

For example: (loop blinking red border)

[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat animations:^{
    [redBorder setAlpha:0]; //first part of animation
    [redBorder setAlpha:0.5]; //second part of animation
} completion:nil];

Upvotes: 1

Related Questions