Skip to content

Instantly share code, notes, and snippets.

@msewell
Created January 24, 2018 16:37
Show Gist options
  • Save msewell/cd5e58a782279951be00ac46887fab54 to your computer and use it in GitHub Desktop.
Save msewell/cd5e58a782279951be00ac46887fab54 to your computer and use it in GitHub Desktop.
UIControl.addAction(for:action:)
extension UIControl {
private class ClosureSleeve {
let closure: () -> Void
init(attachTo attachee: AnyObject, closure: @escaping () -> Void) {
self.closure = closure
objc_setAssociatedObject(attachee, "\(Int.random())", self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
@objc
func invoke() {
closure()
}
}
func addAction(for controlEvents: UIControlEvents, action: @escaping () -> Void) {
let sleeve = ClosureSleeve(attachTo: self, closure: action)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment