[英]CABasicAnimation disappear when home button is pushed
我正在实现一个游戏,其中有一些 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;
}
当我的应用程序进入后台时,因为用户按下主页按钮,动画正确设置为暂停,但是当我重新打开我的应用程序时,动画消失了。
请问我怎么修?
谢谢
这是正确的内置行为。 当您离开应用程序时,所有动画都会从其图层中删除:系统在每个图层上调用removeAllAnimations
。
这通常无关紧要,原因如下:假设您将一个球从 A 点动画到 B 点,并且当用户离开您的应用程序时,动画中的 B 点已经到了一半。 当用户回来时,动画消失了,但球在B 点,所以应用程序可以继续。 所发生的一切只是我们跳过了一些动画部分。
观察UIApplicationWillEnterForegroundNotification
并重新动画CAAnimation
只需在UIViewController
或UIView
类中添加以下代码。 无需恢复或重新开始动画。 它会自己处理:)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive:) name:UIApplicationWillEnterForegroundNotification object:nil];
-(void)becomeActive : (NSNotification*)notification
{
NSLog(@"app become active");
}
当视图从可见区域消失时(不仅仅是当应用程序进入后台时),所有动画都会被删除。 为了修复它,我创建了自定义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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.