Created
April 21, 2016 10:12
-
-
Save junpluse/0ba660ab34efbbfd57c257beb44415f5 to your computer and use it in GitHub Desktop.
CAAnimation.on(started:stopped:)
This file contains hidden or 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
import QuartzCore | |
private extension CAAnimation { | |
final class Delegate: NSObject { | |
var startHandlers = Array<StartHandler>() | |
var stopHandlers = Array<StopHandler>() | |
override func animationDidStart(anim: CAAnimation) { | |
startHandlers.forEach { $0(animation: anim) } | |
} | |
override func animationDidStop(anim: CAAnimation, finished flag: Bool) { | |
stopHandlers.forEach { $0(animation: anim, finished: flag) } | |
} | |
} | |
struct AssociatedObjectKey { | |
static var on_delegate: Delegate? | |
} | |
var on_delegate: Delegate { | |
var result = objc_getAssociatedObject(self, &AssociatedObjectKey.on_delegate) as? Delegate | |
if result == nil { | |
result = Delegate() | |
delegate = result | |
objc_setAssociatedObject(self, &AssociatedObjectKey.on_delegate, result, .OBJC_ASSOCIATION_RETAIN) | |
} | |
return result! | |
} | |
} | |
public extension CAAnimation { | |
typealias StartHandler = (animation: CAAnimation) -> Void | |
typealias StopHandler = (animation: CAAnimation, finished: Bool) -> Void | |
func on(started started: StartHandler? = nil, stopped: StopHandler? = nil) -> Self { | |
let delegate = on_delegate | |
if let handler = started { | |
delegate.startHandlers.append(handler) | |
} | |
if let handler = stopped { | |
delegate.stopHandlers.append(handler) | |
} | |
return self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment