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)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…