iPhone等待动画结束

问题描述:

在iPhone应用程序中,我尝试使用setAnimationDidStopSelector捕捉动画结尾。我尝试暂停代码执行,直到动画结束。我试过这个;设置一个全局BOOL变量,在提交动画之前以及在使用while循环等待动画之后将其设置为TRUE。在setAnimationDidStopSelector中,将BOOL变量设置为FALSE,并希望while循环中断。但不幸的是,这不起作用,代码甚至没有落入setAnimationDidStopSelector(我用一些跟踪输出来检查它)。编辑:如果该BOOL变量处理不添加,代码运行到处理程序方法。iPhone等待动画结束

其中动画发生的代码如下:

self.AnimationEnded=FALSE; 
[UIView beginAnimations:NULL context:NULL]; 
[UIView setAnimationDuration:2]; 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; 
// do sth. 
[UIView commitAnimations]; 
while(![self AnimationEnded]); 

而且这是处理程序的代码:

- (void)animationDidStop:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context { 
    printf("abc\n"); fflush(stdout); 
    self.AnimationEnded=true; 
} 

你有什么建议?

直到此循环结束,动画才会启动。这个循环直到动画开始才会完成。

while(![self AnimationEnded]); 

无论你想在动画需要进入animationDidStop方法后要做什么。

+0

? – 2010-04-28 07:16:50

+2

iPhone OS面向运行循环。而不是坐在自己的紧密循环中等待一些事情,注册一个回调或设置一个计时器,让运行循环运行。 – drawnonward 2010-04-28 17:06:45

+1

繁忙的循环是一种可怕的方法,并且从UI线程执行它更糟糕。 – 2012-11-20 17:08:09

您必须调用setAnimationDelegate:来指定您希望在动画停止时调用选择器的对象。假设将您的标志设置为FALSE的方法与您创建动画的类相同,将为self。详情请参阅UIView class reference

+0

我没有得到;编辑我的问题,并添加代码...即使它在外面的动画块, – 2010-04-28 02:29:16

在iOS 4中,您可以设置一个完成块,而不是使用动画委托和处理程序。当动画结束时,这是一种更简单的方法。如果您不支持iOS 4之前的设备,我建议使用它。

你的榜样更改为:

self.animationEnded = NO; 
[UIView animateWithDuration:2 
     animations:^{ /* Do something here */ } 
     completion:^(BOOL finished){ 
      printf("abc\n"); 
      fflush(stdout); 
      self.animationEnded = YES; 
     }]; 

+UIView animateWithDuration:animations:completion:在iOS开发者的网站了解。

试试这个:

__block BOOL done = NO; 
[UIView animateWithDuration:0.3 animations:^{ 
    // do something 
} completion:^(BOOL finished) { 
    done = YES; 
}]; 
// wait for animation to finish 
while (done == NO) 
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]; 
// animation is finished, ok to proceed