2013-05-03 105 views
2

我想在動畫完成後執行doSomethingElse。另一個限制是動畫代碼可以具有不同的持續時間。我怎樣才能做到這一點?謝謝!等待動畫在iOS中完成?

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

例如,這不起作用:

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

您的問題無法從您提供的內容中解決。請參閱下面的答案,以獲得您想要的行爲,您必須能夠看到執行動畫的代碼(此處由doAnimation封裝)。 – isaac 2013-05-03 22:54:23

回答

6

使用塊動畫:

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

我沒有特定的時間,見上面 – 2013-05-03 21:53:23

+0

@ SebastianOberste-Vorth我不明白爲什麼這會是一個問題。你可以通過任何你想要的時間。 – 2013-05-03 21:53:56

+0

我不知道之前的持續時間,它取決於doAnimation函數,這是隨機的 – 2013-05-03 21:55:20

2

您需要能夠訪問您正在運行的動畫的特定實例,以協調每個動畫的完成操作。在你的例子中,[self doAnimation]不會讓我們看到任何動畫,所以你的問題不能用你提供的東西「解決」。

有幾種方法可以實現您想要的效果,但這取決於您正在處理的動畫類型。

在其他的答案所指出的,在視圖上的動畫之後執行代碼的最常見的方式是通過一個completionBlock中:animateWithDuration:completion:另一種方式來處理屬性變化的動畫是的範圍內設置一個CATransaction完成塊交易。

但是,這些特定的方法基本上是爲動畫屬性或層次結構更改視圖。當您的動畫涉及視圖及其屬性時,這是推薦的方式,但不包括您可能在iOS中找到的所有類型的動畫。從你的問題來看,目前還不清楚你使用的是什麼類型的動畫(或者如何,或者爲什麼),但是如果你實際觸及CAAnimations(關鍵幀動畫或一組動畫)的實例,你會通常做的是建立一個委託:

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. 
} 

的一點是,你如何完成處理實現取決於你的動畫是如何實現的。在這種情況下,我們看不到後者,所以我們無法確定前者。

0

從你的意見,我會建議你:

-(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]; 
} 
+0

setAnimationDidStopSelector:如果不在UIView動畫塊中調用,則不執行任何操作。 – isaac 2013-05-03 22:38:30

+0

你是對的,更新了代碼 – Efesus 2013-05-03 22:40:56

17

當你不是動畫的作者,當動畫通過使用交易完成塊結束,你可以得到一個回調:

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