我正在实施一个游戏,其中我有一些CABasicAnimations。 例如,像这样:
CABasicAnimation * borddroit = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
borddroit.fromValue = [NSNumber numberWithFloat:0.0f];
borddroit.toValue = [NSNumber numberWithFloat:749.0f];
borddroit.duration = t;
borddroit.repeatCount = 1;
[ImageSuivante2.layer addAnimation:borddroit forKey:@"borddroit"];
我暂停了这个功能:
-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
layer.speed = 0.0;
layer.timeOffset = pausedTime;
}
当我的应用程序进入后台时,因为用户按下主页按钮,动画在暂停时正确设置,但是当我重新打开我的应用程序时,动画已经消失。
我该怎么办呢?
谢谢
答案 0 :(得分:6)
这是正确的内置行为。当您离开应用程序时,所有动画都会从其图层中删除:系统会在每个图层上调用removeAllAnimations
。
这通常无关紧要,原因如下:假设您将球从A点动画到B点,当用户从您的应用程序切换时,它在动画中位于B点的一半。当用户回来时,动画消失了,但是球在点B,所以应用程序可以继续。所有这一切都是我们跳过了一些动画部分。
答案 1 :(得分:0)
观察UIApplicationWillEnterForegroundNotification
并重新制作CAAnimation
答案 2 :(得分:0)
只需在UIViewController
或UIView
课程中添加以下代码即可。无需恢复或重新开始动画。它将由它自己处理:)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive:) name:UIApplicationWillEnterForegroundNotification object:nil];
-(void)becomeActive : (NSNotification*)notification
{
NSLog(@"app become active");
}
答案 3 :(得分:0)
当视图从可见区域消失时(不仅是当应用进入背景时),所有动画都将被删除。为了解决这个问题,我创建了自定义CALayer
子类并覆盖了2个方法,因此系统不会删除动画-removeAnimation
和removeAllAnimations
:
class CustomCALayer: CALayer {
override func removeAnimation(forKey key: String) {
// prevent iOS to clear animation when view is not visible
}
override func removeAllAnimations() {
// prevent iOS to clear animation when view is not visible
}
func forceRemoveAnimation(forKey key: String) {
super.removeAnimation(forKey: key)
}
}
在要将此层用作主层的视图中,覆盖layerClass
属性:
override class var layerClass: AnyClass {
return CustomCALayer.self
}