0

我有一个基本动画,只需旋转图像,我正在使用核心动画。在 viewWillAppear 方法中,我创建了动画:

gearRotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
gearRotate.repeatCount = HUGE_VALF;
gearRotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
gearRotate.duration = 2;
gearRotate.fromValue = 0;
gearRotate.toValue = [NSNumber numberWithFloat:(360*M_PI)/180];
[gearButton.imageView.layer addAnimation:gearRotate forKey:@"transform.rotation"];


[self stopGear];

我最初调用 stopGear 来暂停动画。我确实在 viewDidLoad 中有这段代码。无论如何,当动画被调用时,它工作正常:

-(void)startGear {
CFTimeInterval pausedTime = [gearButton.imageView.layer timeOffset];
gearButton.imageView.layer.speed = 1.0;
gearButton.imageView.layer.timeOffset = 0.0;
gearButton.imageView.layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [gearButton.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
gearButton.imageView.layer.beginTime = timeSincePause;

}

这种暂停方法也可以正常工作:

-(void)stopGear {
CFTimeInterval pausedTime = [gearButton.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
gearButton.imageView.layer.speed = 0.0;
gearButton.imageView.layer.timeOffset = pausedTime;

}

但是,如果我转到另一个视图然后回到主视图,这一切都会失败。该应用程序运行良好,但如果我去过另一个视图,动画将永远不会运行。

这就是为什么我最初将此代码移动到 viewWillAppear 的原因,认为我需要重新创建动画,但没有 bean。有任何想法吗?

谢谢。

4

2 回答 2

0

gearRotate.repeatCount = HUGE_VALF;您可以使用以下方法代替使用,以便在对另一个视图控制器执行 segue 后保持动画运行:

-(void)startGear {
    [[gearButton.imageView layer] removeAnimationForKey:@"transform.rotation"];
    gearRotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    gearRotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    gearRotate.duration = 2;
    gearRotate.fromValue = 0;
    gearRotate.toValue = [NSNumber numberWithFloat:(360*M_PI)/180];
    [[gearButton.imageView layer] addAnimation:gearRotate forKey:@"transform.rotation"];
    [self performSelector:@selector(startGear) withObject:nil afterDelay:gearRotate.duration];
}
于 2012-09-29T20:06:41.917 回答
0

好的,所以我通过重新思考动画的工作原理来解决这个问题。我现在只是在每次我希望它运行时创建动画:

-(void)startGear {
    gearRotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    gearRotate.repeatCount = HUGE_VALF;
    gearRotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    gearRotate.duration = 2;
    gearRotate.fromValue = 0;
    gearRotate.toValue = [NSNumber numberWithFloat:(360*M_PI)/180];
    [[gearButton.imageView layer] addAnimation:gearRotate forKey:@"transform.rotation"];

}

当我想暂停它时,我只需将其删除:

-(void)stopGear {
    [[gearButton.imageView layer] removeAnimationForKey:@"transform.rotation"];

}

我目前不确定这是否是 Apple 的首选方法,但它运行良好。

于 2012-06-27T07:36:56.293 回答