Search code examples
objective-cblockanimatewithduration

How to return BOOL from animateWithDuration?


I try to create method and return BOOL type from animateWithDuration. But my object seems not detected on completion block. can somebody explain to me, why this can be happen?

+ (BOOL)showAnimationFirstContent:(UIView *)view {
    BOOL status = NO;

    CGRect show = [SwFirstContent rectFirstContentShow];

    [UIView animateWithDuration:DURATION
                          delay:DELAY
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{ view.frame = show; }
                     completion:^( BOOL finished ) {
                         status = YES;
                     }];
    return status;
}

thanks advance.


Solution

  • You are setting the status value inside a block which will be executed asynchronously. Meaning, your return statement is NOT guaranteed to be executed after the block is executed. To know when your animation is finished you need to declare your method in a different way.

    + (void)showAnimationFirstContent:(UIView *)view completion:(void (^)(void))callbackBlock{
    
        CGRect show = [SwFirstContent rectFirstContentShow];
    
        [UIView animateWithDuration:DURATION
                              delay:DELAY
                            options:UIViewAnimationOptionBeginFromCurrentState
                         animations:^{ view.frame = show; }
                         completion:^( BOOL finished ) {
                             callbackBlock();
                         }];
    }
    

    And you can call this method like this:

    [MyClass showAnimationFirstContent:aView completion:^{
    //this block will be executed when the animation will be finished
        [self doWhatEverYouWant];
    }];
    

    You may want to read a bit more about how block works.

    Hope this helps.