Skip to content

Instantly share code, notes, and snippets.

@tom-biel
Last active October 19, 2019 22:49
Show Gist options
  • Save tom-biel/5d586144d3690af2d4d7c57bf2446aea to your computer and use it in GitHub Desktop.
Save tom-biel/5d586144d3690af2d4d7c57bf2446aea to your computer and use it in GitHub Desktop.
Add ability for create NSGestureRecognizer with closure
import Cocoa
extension NSGestureRecognizer {
private class CallbackWrapper {
let callback: NSGestureRecognizer.Callback
weak var gestureRecognizer: NSGestureRecognizer?
init(callback:@escaping NSGestureRecognizer.Callback) {
self.callback = callback
}
@objc func action(_ sender:NSGestureRecognizer) {
callback(gestureRecognizer!)
}
}
fileprivate struct AssociatedObjectKeys {
static var callbackWrapper = "NSGestureRecognizer_CallbackWrapper"
}
typealias Callback = ((NSGestureRecognizer) -> Void)
convenience init(callback: @escaping Callback) {
let wrapper = CallbackWrapper(callback: callback)
self.init(target:wrapper, action:#selector(CallbackWrapper.action(_:)))
// use associated object to retain wrapper as
// NSGestureRecognizer target uses weak reference
objc_setAssociatedObject(self, &AssociatedObjectKeys.callbackWrapper, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
wrapper.gestureRecognizer = self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment