Search code examples
ioscocoa-touchcore-animation

Can I use setAnimationRepeatCount: within a UIView animation block?


I want to make a button blink using UIAnimation's block style methods, particularly:

animateWithDuration:delay:options:animations:completion

One of the things I think I need to set is the 'AnimationRepeatCount' property - can this be set inside the animation block code like this?

- (void)animateItemWithBlinking:(BOOL)blinking {

    __block BOOL isInBlinkState = blinking;

    if (!isBlinking)
    {       
        // Start blinking                
        [UIView animateWithDuration:0.50f 
            delay:0 
            options:UIViewAnimationCurveLinear
            animations:^{
                // Can I call the AnimationRepeat setter here or 
                // should it be elsewhere outside this block?
                [UIView setAnimationRepeatCount:1000];
                [UIView setAnimationRepeatAutoreverses:YES];

                [button setAlpha:0.0f];        
            } completion:^(BOOL finished) {
                // eventually, this is a value that I want the method to return
                isInBlinkState = !isInBlinkState;        
        }];         
    }
    else
    {
        // Stop blinking
        [UIView animateWithDuration:0.30f 
            delay:0 
            options:UIViewAnimationOptionAllowUserInteraction
            animations:^{
                // Stop blinking - reset everything
                [UIView setAnimationBeginsFromCurrentState:YES];
                [UIView setAnimationRepeatCount:1];

                [button setAlpha:1.0f];        
        } completion:^(BOOL finished) {
            // eventually, this is a value that I want the method to return
            isInBlinkState = !isInBlinkState;        
        }];
    }
}

Prior to block-based calls, my original method looked like this:

- (void)animateItemWithBlinking:(BOOL) blinking {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.50f];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];

    if( !blinking ) {       
        // Start it
        [UIView setAnimationRepeatCount:1000];
        [UIView setAnimationRepeatAutoreverses:YES];

        [button setAlpha:0.0f];                
    } else {
        // Stop it
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationRepeatCount:1];

        [button setAlpha:1.0f];        
    }
    blinking = !blinking;
    [UIView commitAnimations];
}

Solution

  • Yes, you can set it inside the block, and it will do what you'd expect.