2010-03-18 28 views
17

我正在使用CAKeyframeAnimation爲沿着CGPath的視圖設置動畫效果。當動畫完成後,我希望能夠調用其他方法來執行另一個動作。有沒有一個好的方法來做到這一點?如何在CAKeyframeAnimation完成時指定選擇器?

我已經看過使用UIView的setAnimationDidStopSelector :,但是從文檔看起來它只適用於在UIView動畫塊(beginAnimations和commitAnimations)中使用。爲了以防萬一,我也試了一下,但似乎並不奏效。

下面是一些示例代碼(這是一個自定義的UIView子類方法中):

// These have no effect since they're not in a UIView Animation Block 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];  

// Set up path movement 
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"path"]; 
pathAnimation.calculationMode = kCAAnimationPaced; 
pathAnimation.fillMode = kCAFillModeForwards; 
pathAnimation.removedOnCompletion = NO; 
pathAnimation.duration = 1.0f; 

CGMutablePathRef path = CGPathCreateMutable(); 
CGPathMoveToPoint(path, NULL, self.center.x, self.center.y); 

// add all points to the path 
for (NSValue* value in myPoints) { 
    CGPoint nextPoint = [value CGPointValue]; 
    CGPathAddLineToPoint(path, NULL, nextPoint.x, nextPoint.y); 
} 

pathAnimation.path = path; 
CGPathRelease(path); 

[self.layer addAnimation:pathAnimation forKey:@"pathAnimation"]; 

我正在考慮,應該工作,但似乎並沒有像最好的辦法一種解決方法,是使用NSObject的performSelector:withObject:afterDelay :.只要我設置的延遲等於動畫的持續時間,那麼它應該沒問題。

有沒有更好的方法?謝謝!

回答

34

或者你可以附上你的動畫:

[CATransaction begin]; 
[CATransaction setCompletionBlock:^{ 
        /* what to do next */ 
       }]; 
/* your animation code */ 
[CATransaction commit]; 

,並設置完畢塊來處理你需要做什麼。

4

Swift 3語法爲answer

CATransaction.begin() 
CATransaction.setCompletionBlock { 
    //Actions to be done after animation 
} 
//Animation Code 
CATransaction.commit() 
相關問題