ios - 当应用程序进入后台并在 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
否则动画背景暂停和前景恢复是否有任何解决方案。
解决方案
请参阅此线程以获得相当详细的讨论:
如何暂停和恢复 UIView.animateWithDuration
到目前为止,暂停和恢复动画的最简单和最干净的方法是使用 a UIViewPropertyAnimator
,如其中一个答案中所述。
当您收到通知您的应用程序被暂停时,您应该能够捕获动画的完成百分比,然后编写代码以在您的应用程序恢复时重新建立动画,并将其设置为动画中的同一点。
推荐阅读
- css - css-之后。如何隐藏最后一个伪元素
- python - 具有 2 个数值变量和 1 个分类变量的热图
- r - 解释素数的单行代码
- python - 确定网站是否是网上商店
- python - 为列表中的 URL 运行 python 脚本并输出到 txt
- javascript - 将字符串转换为带两位小数,然后将两者相加
- amazon-web-services - 有没有办法删除使用对象锁定“合规”保留模式创建的 S3 对象?
- python - 使用请求库的身份验证不起作用
- google-apps-script - 将电子表格饼图转换为保留其样式的文本文档?
- docker - 在 Windows 容器模式下初始化 Docker 时,Kubernetes 服务不可见