Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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 {
var beginClosure: LayerAnimationBeginClosure?
var completionClosure: LayerAnimationCompletionClosure?
// MARK: - Protocol Implementations
// MARK: CAAnimation (Informal)
override func animationDidStart(animation: CAAnimation) {
guard let beginClosure = beginClosure else { return }
beginClosure(animation)
}
override 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