如何在按下主页按钮后在后台为图像设置动画?

时间:2013-06-17 07:53:23

标签: iphone ios objective-c

我是ios开发的新手。我正在我的项目中使用轮子图像。动画在前景模式下工作正常。之后,我按下主页按钮。现在我重新启动应用程序轮子动画不起作用。这是我的代码:

CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.fromValue = [NSNumber numberWithFloat:0.0f];
animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
animation.duration = 1.0f;
animation.repeatCount = INFINITY;
[imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];

2 个答案:

答案 0 :(得分:3)

试试这个,

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationWillEnterForegroundNotification object:nil];

}

- (void)addAnimation:(NSNotification *)notificaiton
 {
 CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
 animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
 animation.toValue = [NSNumber numberWithFloat:0.0f];
 animation.duration = 4.0f;
 animation.repeatCount = INFINITY;
 [imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
 [imageRight.layer addAnimation:animation forKey:@"SpinAnimation"];
 }
//-----------------------------------------------------------------------------

//How to remove an observer for NSNotification

      [[NSNotificationCenter defaultCenter] removeObserver:self];

答案 1 :(得分:0)

当您的应用暂停(发送到后台)时,所有动画和计时器都会被淘汰。这是为了节省电池。 当您的应用程序被带到前台时,您必须再次启动动画。

您可以在app代理中为我们- (void)applicationDidBecomeActive:(UIApplication *)application

或者在视图控制器中监听包含动画的UIApplicationDidBecomeActiveNotification通知。