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 tap myPauseButton
, and resume the animation if I tap it again.
2 functions to pause and resume animation, I take from here and convert to Swift.
func pauseLayer(layer: CALayer) {
let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: 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(), from: nil) - pausedTime
layer.beginTime = timeSincePause
}
I have a button to pause or resume the animation which is initiated in viewDidLoad
:
var pause = false
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 10.5) {
self.image.transform = CGAffineTransformMakeTranslation(0.0, 200)
}
}
@IBAction func changeState() {
let layer = image.layer
pause = !pause
if pause {
pauseLayer(layer)
} else {
resumeLayer(layer)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With