Created
January 4, 2016 22:01
-
-
Save nazywamsiepawel/e462193f299187d0fc8e to your computer and use it in GitHub Desktop.
Pause / Resume CABasicAnimation with Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func pauseAnimation(){ | |
var pausedTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) | |
layer.speed = 0.0 | |
layer.timeOffset = pausedTime | |
} | |
func resumeAnimation(){ | |
var pausedTime = layer.timeOffset | |
layer.speed = 1.0 | |
layer.timeOffset = 0.0 | |
layer.beginTime = 0.0 | |
let timeSincePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime | |
layer.beginTime = timeSincePause | |
} |
Works perfectly!
Works great when speed is 1.0, but not when it's for example 0.1 :o
The above is an adaptation from Core Animation Programming Guide: Pausing and Resuming Animations. But convertTime(_:fromLayer:)
has been renamed to convertTime(_:from:)
. And we can use let
. Thus:
func pauseAnimation() {
let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil)
layer.speed = 0
layer.timeOffset = pausedTime
}
func resumeAnimation() {
let pausedTime = layer.timeOffset
layer.speed = 1
layer.timeOffset = 0
layer.beginTime = 0
let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
layer.beginTime = timeSincePause
}
Works perfectly on iOS 15.4, and my code about animation goes:
static let animationKey = "ProgressLayerGrowAnimation"
func progressAnimation() {
if let CAKeys = progressLayer.animationKeys(), CAKeys.contains(Self.animationKey) {
let pausedTime = progressLayer.timeOffset
progressLayer.speed = 1.0
progressLayer.timeOffset = 0.0
progressLayer.beginTime = 0.0
let timeSincePause = progressLayer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
progressLayer.beginTime = timeSincePause
return
}
let circularProgressAnimation = <#whatever animation#>
progressLayer.add(circularProgressAnimation, forKey: Self.animationKey)
}
func resetAnimation() {
progressLayer.removeAnimation(forKey: Self.animationKey)
}
func pauseAnimation() {
let pausedTime = progressLayer.convertTime(CACurrentMediaTime(), from: nil)
progressLayer.speed = 0.0
progressLayer.timeOffset = pausedTime
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was very helpful for me. Thank you!