iOS - multiple animation blocks?

喜夏-厌秋 提交于 2019-12-05 05:55:37

问题


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){

         }];

}];

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10019696/ios-multiple-animation-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!