等待animation在iOS中完成?

我想在animation完成后执行doSomethingElse。 另一个限制是animation代码可以具有不同的持续时间。 我怎样才能做到这一点? 谢谢!

-(void) doAnimationThenSomethingElse { [self doAnimation]; [self doSomethingElse]; } 

这例如不起作用:

 animationDuration = 1; [UIView animateWithDuration:animationDuration animations:^{ [self doAnimation]; } completion:^(BOOL finished) { [self doSomethingElse]; } ]; 

如果您不是animation的作者,则可以在animation使用事务完成块结束时获得callback:

 [CATransaction setCompletionBlock:^{ // doSomethingElse }]; // doSomething 

使用块animation:

 [UIView animateWithDuration:animationDuration animations:^{ // Put animation code here } completion:^(BOOL finished) { // Put here the code that you want to execute when the animation finishes } ]; 

您需要能够访问您正在运行的animation的特定实例,以便协调每个animation的完成操作。 在你的例子中,[self doAnimation]不会让我们看到任何animation,所以你的问题不能用你提供的东西“解决”。

有几种方法可以达到你想要的效果,但这取决于你正在处理的是什么types的animation。

正如在其他答案中指出的那样,在视图上animation之后执行代码的最常见方法是传递一个completionBlock: animateWithDuration:completion:处理属性更改animation的另一种方法是在该范围内设置一个CATransaction完成块交易。

但是,这些特定的方法基本上是为animation属性或层次结构更改视图。 当您的animation涉及视图及其属性时,这是推荐的方式,但不包括您可能在iOS中find的所有types的animation。 从你的问题来看,目前还不清楚你正在使用什么types的animation(或者如何,或者为什么),但是如果你实际上触及了CAAnimations(关键帧animation或者一组animation)的实例,通常是设置一个委托:

 CAAnimation *animation = [CAAnimation animation]; [animation setDelegate:self]; [animatedLayer addAnimation:animation forKeyPath:nil]; // Then implement the delegate method on your class - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag { // Do post-animation work here. } 

关键是,你的完成处理是如何实现的取决于你的animation是如何实现的。 在这种情况下我们看不到后者,所以我们不能确定前者。

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html

有UIView文档,向下滚动到

用块animation视图

animation视图

看超链接跳转到页面的不同部分,解释如何animation视图,你想要的那些是在“animation块与块”阅读方法的名称使他们自我解释

从你的意见,我会推荐你​​:

 -(void) doAnimation{ [self setAnimationDelegate:self]; [self setAnimationDidStopSelector:@selector(finishAnimation:finished:context:)]; [self doAnimation]; } - (void)finishAnimation:(NSString *)animationId finished:(BOOL)finished context:(void *)context { [self doSomethingElse]; }