How do I know if several blocks have completed before a decision is made?

I use animateWithDuration:animations:completion:to move several elements of my user interface (about 4 elements) before the call removeFromSuperview:.

My question is, how can I find out that all these animations completed before the call removeFromSuperview:?

+5
source share
3 answers

Good to answer my own question.

I ended up doing something like this:

    // Create dispatch queue & group
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    // Two group enters
    dispatch_group_enter(group);
    dispatch_group_enter(group);

    // (notice the group parameter in dispatch_group_leave)
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.frame = CGRectMake( self.pickerView.frame.origin.x
                                           , self.view.bounds.size.height + self.pickerView.frame.size.height/2
                                           , self.pickerView.frame.size.width
                                           , self.pickerView.frame.size.height);
    } completion:^(BOOL finished){
        dispatch_group_leave(group);
    }]; 


    [UIView animateWithDuration:0.3 animations:^{
        self.navigationBar.frame = CGRectMake( self.navigationBar.frame.origin.x
                                              , -self.navigationBar.frame.size.height
                                              , self.navigationBar.frame.size.width
                                              , self.navigationBar.frame.size.height);
    } completion:^(BOOL finished){
        dispatch_group_leave(group);
    }];

    // Finishing callback
    dispatch_group_notify(group, queue, ^{
        [self.view removeFromSuperview];
    });

    // Release the group
    dispatch_release(group);

Hope this can serve as an example for someone else.

+9
source

You can also use CATransaction. It will capture any built-in animations:

 [CATransaction begin];
 [CATransaction setCompletionBlock:^{ // all animations finished here }];
 [UIView animateWithDuration...
 [UIView animateWithDuration...
 ...
 [CATransaction commit];

This will allow you not to follow the animation yourself.

+1
source

Create a submit queue, pause it for the number of animations you make. Add a block to the queue that will be removed from the supervisor. At the end of each animation, the paused queue resumes. When the latter is completed, the block in the queue will be launched.

0
source

All Articles