Last active
October 19, 2019 22:49
-
-
Save tom-biel/5d586144d3690af2d4d7c57bf2446aea to your computer and use it in GitHub Desktop.
Add ability for create NSGestureRecognizer with closure
This file contains 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 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