首页 > 解决方案 > 当应用程序进入后台并在 Swift 中以前台模式恢复时暂停动画

问题描述

我正在使用UIViewAnimation完成块为视图设置动画。当应用程序进入后台模式时,需要暂停动画并从它在前台模式暂停的位置恢复。我正在使用以下方法进行暂停和恢复:-

func resume() {
    let pausedTime: CFTimeInterval = layer.timeOffset
    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0
    let timeSincePause: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    layer.beginTime = timeSincePause
}
func pause() {
    let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

如果应用程序在前台,这两种方法都可以正常工作。但是如果应用程序进入后台,动画完成并首先调用完成块,然后调用暂停方法,但由于动画已经完成而没有工作。UIApplication.willEnterForegroundNotification我用过UIApplication.didEnterBackgroundNotification

根据这个答案使用Core Animation而不是UIViewAnimation然后恢复/暂停将起作用。但是我没有得到使用动画的CABasicAnimation方法UIView

        UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: {[weak self] in
        if let _self = self {
            _self.frame.size.width = width
        }
    }) { [weak self] (finished) in
        // do something after finished animation
    }

如果使用Core Animation我该怎么做?UIView否则动画背景暂停和前景恢复是否有任何解决方案。

标签: iosswiftcore-animationuiviewanimationbackground-foreground

解决方案


请参阅此线程以获得相当详细的讨论:

如何暂停和恢复 UIView.animateWithDuration

到目前为止,暂停和恢复动画的最简单和最干净的方法是使用 a UIViewPropertyAnimator,如其中一个答案中所述。

当您收到通知您的应用程序被暂停时,您应该能够捕获动画的完成百分比,然后编写代码以在您的应用程序恢复时重新建立动画,并将其设置为动画中的同一点。


推荐阅读