Josh Kahane Josh Kahane - 6 months ago 54
Objective-C Question

UIViewAnimationOptionRepeat Completion?

I am doing a very simple repeating animation to fade a label in and out, seen below. I assumed the completion block would be called every time the animation finishes, but when using

UIViewAnimationOptionRepeat
it is never called. So how am I supposed to stop this animation?

I know I can use
[self.lbl.layer removeAllAnimations];
, however that ends its very abruptly. I want to know when it has finished a cycle of the animation so I can stop it at that time.

[UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut animations:^{
self.lbl.alpha = 0;

} completion:^(BOOL finished){
if (finished) NSLog(@"done");

}];


Any help really appreciated, thanks!

Answer

maybe this kind of solution using a selector can help you:

- (void) animateTextWithMax:(NSNumber *)max current:(NSNumber *)current
{
    NSLog(@"max = %d, current = %d",max.intValue, current.intValue);
    textlabel.alpha = 1.0f;
    [UIView animateWithDuration:1.0f delay:0 options:UIViewAnimationOptionAutoreverse
                     animations:^{
                         textlabel.alpha = 0.0f;
                     }completion:^(BOOL finished){
                         NSLog(@"finished");
                         if (current.intValue < max.intValue) {
                             [self performSelector:@selector(animateTextWithMax:current:) withObject:max withObject:[NSNumber numberWithInteger:(current.intValue+1)]];
                         }

                     }];
}

then you can call the animation by this way:

[self animateTextWithMax:[NSNumber numberWithInt:3] current:[NSNumber numberWithInt:0]];

Maybe this is not the best solution because you are not using the UIViewAnimationOptionRepeat option, but I think it can work.

I hope this helps you.