UIView's animateWithDuration delay not delaying animation

Asem H. picture Asem H. · Nov 23, 2011 · Viewed 16.9k times · Source

I am trying to perform an animation on a label where a flip animation happens and after it is done and after a delay, The text of the label changes.

It seems that the delay never happens. The text immediately changes after the flip completes although I am using UIView animateWithDuration:0.5 delay:4.0 in the completion block. If Instead I do a performSelector with Delay in the completion block (the commented statement) it works as expected. Any idea why the delay value is being ignored?

- (void) flipShapeWithText:(NSString *)text {

    [UIView transitionWithView:someLabel duration:0.15 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        someLabel.text = text;  
    }completion:^ (BOOL finished){
//        [self performSelector:@selector(updateLabelText:) withObject: @"New Text" afterDelay:4.0];
    [UIView animateWithDuration:0.5
                              delay:4.0
                            options: UIViewAnimationOptionTransitionCrossDissolve
                         animations:^{
                             currentShapeNameLabel.text =  @"New Text" ;}
                         completion:nil];
    }];
}

Answer

XJones picture XJones · Nov 23, 2011

The delay param of animateWithDuration:delay:options:animations:completion specifies the delay before the animation occurs. You are setting the text within the animation block so after the delay is over, the animations begin which immediately changes the text as that change is not animatable. To do what you want, change the text in the completion block as follows:

    [UIView animateWithDuration:0.5
                          delay:4.0
                        options: UIViewAnimationOptionTransitionCrossDissolve
                     animations:^{ // anything animatable }
                     completion:^(BOOL finished) {
                         currentShapeNameLabel.text =  @"New Text" ;}];

You can eliminate the delay if you want the animation to start immediately. If you want the text change to happen 4 secs after the animation completes add that delay in the completion block either with dispatch_after() or performSelector:withDelay:.