简体   繁体   English

当应用程序进入后台时暂停动画并在 Swift 中以前台模式恢复

[英]Pause animation when app goes background and resume in foreground mode in Swift

I am animating a view using UIViewAnimation with completion block.我正在使用带有完成块的UIViewAnimation为视图设置动画。 When app goes to background mode need to pause the animation and resume it from where it paused in foreground mode.当应用程序进入后台模式时,需要暂停动画并从它在前台模式中暂停的地方恢复它。 I am using bellow methods for pause and resume:-我正在使用波纹管方法进行暂停和恢复:-

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
}

Those two methods works fine if app is in foreground.如果应用程序在前台,这两种方法都可以正常工作。 but if app goes to background, animation finished and completion block called first then pause method called but not worked as animation already finished.但是如果应用程序进入后台,动画完成并首先调用完成块,然后调用暂停方法,但不会像动画已经完成那样工作。 I used UIApplication.willEnterForegroundNotification and UIApplication.didEnterBackgroundNotification我使用了UIApplication.willEnterForegroundNotificationUIApplication.didEnterBackgroundNotification

According to this answer use Core Animation instead of UIViewAnimation and then the resume/pause will work.根据这个答案使用Core Animation而不是UIViewAnimation然后恢复/暂停将起作用。 But I didn't get the way to use CABasicAnimation instead of UIView animation.但我没有得到使用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
    }

If use Core Animation how can I do it?如果使用Core Animation我该怎么做? else is there any solution for UIView animation background pause and foreground resume.否则是否有UIView动画背景暂停和前景恢复的任何解决方案。

See this thread for a fairly detailed discussion:有关相当详细的讨论,请参阅此线程:

How to pause and resume UIView.animateWithDuration 如何暂停和恢复 UIView.animateWithDuration

By far the easiest and cleanest way to pause and resume animation is to use a UIViewPropertyAnimator ,as mentioned in one of those answers.到目前为止,暂停和恢复动画的最简单和最干净的方法是使用UIViewPropertyAnimator ,如这些答案之一所述。

You should be able to capture the percent complete of the animation when you get notified that your app is being suspended, and then write code to re-establish the animation when your app resumes, and set it to the same point in the animation.当您收到应用程序暂停的通知时,您应该能够捕获动画的完成百分比,然后编写代码以在应用程序恢复时重新建立动画,并将其设置为动画中的相同点。

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

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