How to pause and resume UIView.animateWithDuration

I have an image, I animate it with this code, in viewDidAppear:

UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{ self.myImage.transform = CGAffineTransformMakeTranslation(0.0, 200) }, completion: nil) 

I want to pause the animation when I click myPauseButton , and resume the animation if I touch it again.

+5
source share
2 answers

2 functions for pausing and resuming animation, I take from here and convert to Swift.

 func pauseLayer(layer: CALayer) { let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) layer.speed = 0.0 layer.timeOffset = pausedTime } func resumeLayer(layer: CALayer) { let pausedTime: CFTimeInterval = layer.timeOffset layer.speed = 1.0 layer.timeOffset = 0.0 layer.beginTime = 0.0 let timeSincePause: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime layer.beginTime = timeSincePause } 

I have a button to pause or resume the animation that is initialized in viewDidLoad :

 var pause = false override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{ self.image.transform = CGAffineTransformMakeTranslation(0.0, 200) }, completion: nil) } @IBAction func changeState() { let layer = image.layer pause = !pause if pause { pauseLayer(layer) } else { resumeLayer(layer) } } 
+16
source

Here is the version of this Swift 3+ answer, I moved this function to an extension

 extension CALayer { func pause() { let pausedTime: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil) self.speed = 0.0 self.timeOffset = pausedTime } func resume() { let pausedTime: CFTimeInterval = self.timeOffset self.speed = 1.0 self.timeOffset = 0.0 self.beginTime = 0.0 let timeSincePause: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil) - pausedTime self.beginTime = timeSincePause } } 
+5
source

Source: https://habr.com/ru/post/1237089/


All Articles