Skip to content

Instantly share code, notes, and snippets.

@adilo
Last active December 27, 2016 10:13
Show Gist options
  • Save adilo/67f41692936743e7d8b7b339d64906d9 to your computer and use it in GitHub Desktop.
Save adilo/67f41692936743e7d8b7b339d64906d9 to your computer and use it in GitHub Desktop.
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 -
private class LayerAnimationDelegate: NSObject, CAAnimationDelegate {
var beginClosure: LayerAnimationBeginClosure?
var completionClosure: LayerAnimationCompletionClosure?
// MARK: - Protocol Implementations
// MARK: CAAnimation (Informal)
func animationDidStart(_ anim: CAAnimation) {
guard let beginClosure = beginClosure else { return }
beginClosure(anim)
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard let completionClosure = completionClosure else { return }
completionClosure(anim, flag)
}
}
// MARK: - CALayer Extension -
extension CALayer {
// MARK: - Conveniences for Adding Animations
func add(animation: CAAnimation) {
add(animation, forKey: nil)
}
func add(animation: CAAnimation,forKey key: String?, completionClosure: LayerAnimationCompletionClosure?) {
add(animation: animation, forKey: key, beginClosure: nil, completionClosure: completionClosure)
}
func add(animation: CAAnimation, forKey key: String?, beginClosure: LayerAnimationBeginClosure?, completionClosure: LayerAnimationCompletionClosure?) {
let animationDelegate = LayerAnimationDelegate()
animationDelegate.beginClosure = beginClosure
animationDelegate.completionClosure = completionClosure
animation.delegate = animationDelegate
add(animation, forKey: key)
}
func replace(animation: CAAnimation, forKey key: String) {
replace(animation: animation, forKey: key, beginClosure: nil, completionClosure: nil)
}
func replace(animation: CAAnimation, forKey key: String, completionClosure: LayerAnimationCompletionClosure?) {
replace(animation: animation, forKey: key, beginClosure: nil, completionClosure: completionClosure)
}
func replace(animation: CAAnimation, forKey key: String, beginClosure: LayerAnimationBeginClosure?, completionClosure: LayerAnimationCompletionClosure?) {
removeAnimation(forKey: key)
add(animation: 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