繁体   English   中英

当应用程序转到后台时暂停和恢复UIViewAnimation

[英]Pause and Resume UIViewAnimation when app goes to background

我正在制作一个视图,我想暂停它并恢复它。

使用苹果指南我创建了一个CALayer扩展

extension CALayer {

    func pause() {
        var pauseTime = self.convertTime(CACurrentMediaTime(), fromLayer: nil)
        self.speed = 0.0
        self.timeOffset = pauseTime
    }

    func resume() {
        var pausedTime = self.timeOffset
        self.speed = 1.0
        self.timeOffset = 0.0
        self.beginTime = 0.0
        var timeSincePause = self.convertTime(CACurrentMediaTime(), toLayer: nil) - pausedTime

        self.beginTime = timeSincePause
    }
}

此代码完美地运行,除非该应用程序转到后台。 当我将应用程序带回到前台时,动画已完成(即使时间未通过),并且当我单击“恢复”时它不会再次启动。

好。 我尝试动画CALayer,但我有同样的问题。

extension CALayer {

   func animateY(newY:CGFloat,time:NSTimeInterval,completion:()->Void){
    CATransaction.begin()
    CATransaction.setCompletionBlock(completion)
    let animation = CABasicAnimation(keyPath: "position.y")
    animation.fromValue = self.position.y
    animation.toValue  = newY
    animation.duration = time
    animation.delegate = self
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.removedOnCompletion = false // don't remove after finishing
    self.position.y = newY
    self.addAnimation(animation, forKey: "position.y")
    CATransaction.flush()

  }
}

我建议使用CABasicAnimation 你的简历/暂停方法应该没问题,因为它们来自这个答案。 您应该尝试使用Core Animation而不是UIViewAnimation ,然后恢复/暂停将起作用。

然后,您可以注册两个通知UIApplicationWillEnterForegroundNotificationUIApplicationDidEnterBackgroundNotification以完全控制暂停/恢复操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM