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

时间:2015-06-02 13:22:08

标签: ios swift uiviewanimation

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

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

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()

  }
}

1 个答案:

答案 0 :(得分:0)

我建议使用CABasicAnimation。您的简历/暂停方法应该没问题,因为它们来自此answer.您应该尝试使用Core Animation代替UIViewAnimation,然后恢复/暂停将起作用。

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