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

Dar*_*ren 19 iphone core-animation cakeyframeanimation catransaction

我正在使用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"];
Run Code Online (Sandbox Code Playgroud)

我正在考虑应该工作的解决方法,但似乎不是最好的方法,是使用NSObject的performSelector:withObject:afterDelay:.只要我将延迟设置为等于动画的持续时间,那么它应该没问题.

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

zsk*_*nik 36

或者您可以使用以下内容附上动画:

[CATransaction begin];
[CATransaction setCompletionBlock:^{
                   /* what to do next */
               }];
/* your animation code */
[CATransaction commit];
Run Code Online (Sandbox Code Playgroud)

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


ken*_*ytm 23

CAKeyframeAnimation是CAAnimation的子类.CAAnimation 有一处delegate房产.委托可以实现该-animationDidStop:finished:方法.其余的应该很容易.


Mav*_*ick 6

Swift 3这个答案的语法。

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