【问题标题】:iOS animation stopped after the background/foreground transitioniOS 动画在背景/前景过渡后停止
【发布时间】:2017-04-17 12:15:19
【问题描述】:

我正在编写一个页面来检查设备是否已链接到系统。 页面每 2 秒发送一次请求,共 6 次,在此期间(可能长达 10 秒)页面显示动画加载循环。

问题是:当我按下主页按钮并立即重新打开应用程序时,动画停止

这是我所知道的:

动画的两种实现方式:

  1. CABasicAnimation:

    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = @(2 * M_PI);
    rotationAnimation.duration = 1.5;
    rotationAnimation.cumulative = YES;
    [loadingCircle.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
  2. UIView animateWithDuration...:

    - (void)rotateView:(UIView *)view {
        [UIView animateWithDuration:0.75 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            view.transform = CGAffineTransformRotate(view.transform, M_PI);
        } completion:^(BOOL finished) {
            if (finished) {
                [self rotateView:view];
            }
        }];
    }
    ...
    - viewDidLoad {
        ...
        [self rotateView:loadingCircle];
    }
    

我知道在第一个实现中,设置rotationAnimation.removedOnCompletion = NO; 将恢复动画。

我的问题是:当我使用第二种实现时,实现相同效果的等效方法是什么。

【问题讨论】:

  • 在appdelegate类中调用applicationDidBecomeActive中的动画方法
  • 我通过在本地班级订阅通知来做到这一点。谢谢。

标签: ios objective-c animation


【解决方案1】:

使用 UIView animateWithDuration 实际上会应用与视图的底层 layer 属性相同的效果,因此您可以像这样暂停和恢复。

func pauseLayer(layer: CALayer) {
    let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

func resumeLayer(layer: CALayer) {
    let pausedTime: CFTimeInterval = layer.timeOffset
    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0
    let timeSincePause: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
    layer.beginTime = timeSincePause
}

抱歉,您必须自己将其翻译成objective-c。感谢 here 提供原始解决方案。

如果您想将代码保留在本地而不是放入应用程序委托中,您可以通过NSNotificationCenter 订阅UIApplicationDidEnterBackgroundNotification 通知。有一个匹配的UIApplicationWillEnterForegroundNotification 通知,您可以使用它在返回时重新启动动画。

【讨论】:

  • 谢谢,我试过通知方法,效果很好。 :]
猜你喜欢
  • 1970-01-01
  • 2010-11-17
  • 2016-10-15
  • 2013-12-09
  • 1970-01-01
  • 2013-10-06
  • 2014-08-01
  • 2015-08-12
  • 1970-01-01
相关资源
最近更新 更多