21

我正在使用 CAKeyframeAnimation 沿 CGPath 为视图设置动画。动画完成后,我希望能够调用其他方法来执行其他操作。有没有好的方法来做到这一点?

我已经看过使用 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:。只要我将延迟设置为等于动画的持续时间,就应该没问题。

有没有更好的办法?谢谢!

4

3 回答 3

37

或者,您可以将动画附上:

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

并设置完成块来处理你需要做的事情。

于 2012-06-19T09:39:40.357 回答
24

CAKeyframeAnimation 是 CAAnimation 的子类。CAAnimation 中有一个delegate属性。委托可以实现该-animationDidStop:finished:方法。其余的应该很容易。

于 2010-03-18T07:46:36.980 回答
7

这个答案的Swift 3语法。

CATransaction.begin()
CATransaction.setCompletionBlock {
    //Actions to be done after animation
}
//Animation Code
CATransaction.commit()
于 2017-01-24T10:40:10.537 回答