在segue / view转换后,iOS Core Animation失败

时间:2012-06-26 11:21:49

标签: ios5 core-animation segue

我有一个基本动画,只是旋转图像,我正在使用Core Animation。在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。有什么想法吗?

感谢。

2 个答案:

答案 0 :(得分: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的首选方法,但它能够稳定运行。

答案 1 :(得分: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];
}