简体   繁体   中英

Pause and Resume UIViewAnimation when app goes to background

I am animating a view and I want to pause it and resume it.

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.

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()

  }
}

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.

Then you can register for the two notifications UIApplicationWillEnterForegroundNotification and UIApplicationDidEnterBackgroundNotification to have full control over the pause/resume actions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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