0
votes

I'm animating every UIView in an array and want to know, when all animations are finished. For example: I'm showing 10 UIViews on a ViewController with a simple scale animation and for every UIView a small delay. After all 10 animations finished, I would like to do another animation in the completion block.

How do I know when all animations are finished?

4

4 Answers

4
votes

If your UIViews are delayed sequentially, the last one you queue will be the last one to finish. Just do your stuff in its completion block.

Alternatively, you could do something like:

__block int finishedViews = 0;
[UIView animateWithDuration:... completion:^(BOOL finished) {
  if (++finishedViews == numberOfViews) {
    // do stuff.
  }
}];
2
votes

Let say you have in your UIViewController the property NSArray *arrayOfViews which contains the views you want to animate. What you want could be something like this :

-(void)animateTheViews
{
    __block int nbTerminated = 0;
    for(UIView *aView in arrayOfViews)
    {
        [UIView animateWithDuration:/*duration time in seconds*/ 
         animations:^{
             //set here the changes for aView

        } completion:^(BOOL finished) {
             nbTerminated++;
             if(nbTerminated==[arrayOfViews count])
             {
                 [self whatToDoWhenFinished];
             }
        }];
    }
}

-(void)whatToDoWhenFinished
{
    //some stuff
}

EDIT

__block is needed for the variable nbTerminated

0
votes

Can you try using group of animations.Every UIView is using an animation. Each animation sends animationDidStart: and animationDidStop:finished: to its delegate. So you can run codes when every and all animations finish. Please take a look at animationgroup enter link description here

0
votes

Try this:

typedef void (^VoidBlock)(void);
typedef void (^BoolBlock)(BOOL flag);

in class interface:

@property (nonatomic, strong)VoidBlock animationBlock;

and to animate:

NSArray *views = @[];

NSMutableArray *mutableViews = [views mutableCopy];

BoolBlock completionBlock = ^(BOOL flag){
    [mutableViews removeObjectAtIndex:0];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//delay
        self.animationBlock();
    });
};

self.animationBlock = ^{
    UIView *view = mutableViews.firstObject;
    [UIView animateWithDuration:0.25 animations:^{
        //animate view
    }completion:completionBlock];
};
self.animationBlock();