Created
January 24, 2018 16:37
-
-
Save msewell/cd5e58a782279951be00ac46887fab54 to your computer and use it in GitHub Desktop.
UIControl.addAction(for:action:)
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
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