Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created August 25, 2017 03:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindresorhus/50d1014b0e35be4675b6917719afb2de to your computer and use it in GitHub Desktop.
Save sindresorhus/50d1014b0e35be4675b6917719afb2de to your computer and use it in GitHub Desktop.
[Alternative] NSControl extension for closure version of `.action`
class SelectorWrapper<T> {
let selector: Selector
let closure: (T) -> Void
init(withClosure closure: @escaping (T) -> Void) {
self.selector = #selector(callClosure)
self.closure = closure
}
@objc
private func callClosure(sender: AnyObject) {
closure(sender as! T)
}
}
var handle: Int = 0
extension NSControl {
typealias ActionClosure = (NSControl) -> Void
var onAction: ActionClosure? {
get {
return nil
}
set {
if let newValue = newValue {
let selectorWrapper = SelectorWrapper<NSControl>(withClosure: newValue)
objc_setAssociatedObject(self, &handle, selectorWrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
action = selectorWrapper.selector
target = selectorWrapper
} else {
action = nil
target = nil
}
}
}
}
@halftrue
Copy link

nice implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment