iOS - multiple animation blocks?

Go To StackoverFlow.com

3

I have multiple animations that have to run as a chain. The way I've been dealing with this is to use a completionHandler and run the next animation block. Is there a cleaner way to deal with this?

[UIView animateWithDuration:1 animations^{

        // perform first animation
     }completion:(BOOL finished){

          [UIView animateWithDuration:1 animations^{

               // perform second animation
          }completion:(BOOL finished){

         }];

}];
2012-04-04 21:44
by aryaxt
You can use blocks to get a very clean result. See: http://xibxor.com/objective-c/uiview-animation-without-nested-hell - Andrew Fuchs 2013-04-04 18:34


10

You can also use animateWithDuration:delay:options:animations:completion: with staggered delays so that they start in order, but typically it's best to do them with completion blocks.

If there are several and it's making the code difficult to read, just factor out the blocks (I'm typing this off the top of my head, so it may not compile):

typedef void (^AnimationBlock)();

AnimationBlock firstAnimation = ^{ ... };
AnimationBlock secondAnimation = ^{ ... };

[UIView animateWithDuration:1 animations:firstAnimation completion:(BOOL finished) {
  [UIView animateWithDuration:1 animations:secondAnimation];}];

You could create a category on UIView that took an array of such blocks and chained them together for you, but then you'd have to deal with all the corner cases. How do you define the timings; how do you deal with aborted animations, etc. The above is probably the best approach in most cases.

2012-04-04 22:04
by Rob Napier


1

I wrote a blog post about this. My approach is to create an animation object that encapsulates the block and other animation properties. You can then pass an array of such objects to another animation object that will execute them in sequence. The code is available on GitHub.

2013-05-21 19:36
by Alejandro
Ads