当CAKeyframeAnimation完成时如何指定选择器?

22

我正在使用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:,尽管这不是最好的方式。只要我将延迟设置为动画的持续时间,那么就应该可以正常工作。

还有更好的方式吗?谢谢!

3个回答

39

或者你可以将动画包含在以下代码中:

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

并设置完成块以处理您需要执行的操作。


25

谢谢!我在查看文档时可能错过了这个。 - Daren
这就是为什么你不应该在这里链接和写答案。所有的链接都已经失效了! - Houman

7

Swift 3语法适用于此答案

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接