CALayer extension for using blocks instead of animation delegates
// | |
// CALayerExtensions.swift | |
// | |
import QuartzCore | |
internal typealias LayerAnimationBeginClosure = (CAAnimation) -> Void | |
internal typealias LayerAnimationCompletionClosure = (CAAnimation, Bool) -> Void | |
// MARK: LayerAnimationDelegate Class - | |
fileprivate class LayerAnimationDelegate: NSObject { | |
var beginClosure: LayerAnimationBeginClosure? | |
var completionClosure: LayerAnimationCompletionClosure? | |
} | |
extension LayerAnimationDelegate (CAAnimationDelegate) { | |
func animationDidStart(animation: CAAnimation) { | |
guard let beginClosure = beginClosure else { return } | |
beginClosure(animation) | |
} | |
func animationDidStop(animation: CAAnimation, finished: Bool) { | |
guard let completionClosure = completionClosure else { return } | |
completionClosure(animation, finished) | |
} | |
} | |
// MARK: - CALayer Extension - | |
extension CALayer { | |
// MARK: - Conveniences for Adding Animations | |
func addAnimation(_ animation: CAAnimation) { | |
addAnimation(animation, forKey: nil) | |
} | |
func addAnimation(_ animation: CAAnimation, forKey key: String?, completionClosure: LayerAnimationCompletionClosure?) { | |
addAnimation(animation, forKey: key, beginClosure: nil, completionClosure: completionClosure) | |
} | |
func addAnimation(_ animation: CAAnimation, forKey key: String?, beginClosure: LayerAnimationBeginClosure?, completionClosure: LayerAnimationCompletionClosure?) { | |
let animationDelegate = LayerAnimationDelegate() | |
animationDelegate.beginClosure = beginClosure | |
animationDelegate.completionClosure = completionClosure | |
animation.delegate = animationDelegate | |
addAnimation(animation, forKey: key) | |
} | |
func replaceAnimation(_ animation: CAAnimation, forKey key: String) { | |
replaceAnimation(animation, forKey: key, beginClosure: nil, completionClosure: nil) | |
} | |
func replaceAnimation(_ animation: CAAnimation, forKey key: String, completionClosure: LayerAnimationCompletionClosure?) { | |
replaceAnimation(animation, forKey: key, beginClosure: nil, completionClosure: completionClosure) | |
} | |
func replaceAnimation(_ animation: CAAnimation, forKey key: String, beginClosure: LayerAnimationBeginClosure?, completionClosure: LayerAnimationCompletionClosure?) { | |
removeAnimationForKey(key) | |
addAnimation(animation, forKey: key, beginClosure: beginClosure, completionClosure: completionClosure) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment