当应用程序进入后台时暂停和恢复 UIViewAnimation [英] Pause and Resume UIViewAnimation when app goes to background
问题描述
我正在动画一个视图,我想暂停它并恢复它.
I am animating a view and I want to pause it and resume it.
使用苹果指南我创建了一个 CALayer 扩展
Using an apple guide I created a 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
}
}
除非该应用程序进入后台,否则此代码运行良好.当我将应用程序带回前台时,动画已完成(即使时间没有过去)并且当我单击恢复"时它不会再次启动.
This code is working perfectly except when that app goes to background. When I bring the App back to foreground animations is finished (even if the time is not pass) and it is not starting again when I click resume.
好的.我尝试为 CALayer 设置动画,但我遇到了同样的问题.
Ok. I tried animating CALayer but I have the same problem.
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
然后恢复/暂停将起作用.
I recommend using CABasicAnimation
. Your resume/pause methods should be fine, since they are from this answer. You should try using Core Animation
instead of UIViewAnimation
and then the resume/pause will work.
然后您可以注册两个通知 UIApplicationWillEnterForegroundNotification
和 UIApplicationDidEnterBackgroundNotification
以完全控制暂停/恢复操作.
Then you can register for the two notifications UIApplicationWillEnterForegroundNotification
and UIApplicationDidEnterBackgroundNotification
to have full control over the pause/resume actions.
这篇关于当应用程序进入后台时暂停和恢复 UIViewAnimation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!