[英]Pause animation when app goes background and resume in foreground mode in Swift
[英]Pause and Resume UIViewAnimation when app goes to background
我正在制作一個視圖,我想暫停它並恢復它。
使用蘋果指南我創建了一個CALayer擴展
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()
}
}
我建議使用CABasicAnimation
。 你的簡歷/暫停方法應該沒問題,因為它們來自這個答案。 您應該嘗試使用Core Animation
而不是UIViewAnimation
,然后恢復/暫停將起作用。
然后,您可以注冊兩個通知UIApplicationWillEnterForegroundNotification
和UIApplicationDidEnterBackgroundNotification
以完全控制暫停/恢復操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.