Created
April 9, 2019 11:22
-
-
Save grav/9fc574de89895460e87ad9d8aa47e95c to your computer and use it in GitHub Desktop.
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
//Parameter is the type of parameter passed in the selector | |
public class ClosureSelector<Parameter> { | |
public let selector : Selector | |
private let closure : ( Parameter ) -> () | |
init(withClosure closure : @escaping ( Parameter ) -> ()){ | |
self.selector = #selector(ClosureSelector.target) | |
self.closure = closure | |
} | |
// Unfortunately we need to cast to AnyObject here | |
@objc func target( param : AnyObject) { | |
closure(param as! Parameter) | |
} | |
} | |
extension UIControl { | |
func addTarget(forControlEvents controlEvents : UIControl.Event, withClosure closure : @escaping (UIControl) -> Void) { | |
let closureSelector = ClosureSelector<UIControl>(withClosure: closure) | |
objc_setAssociatedObject(self, &handle, closureSelector, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
self.addTarget(closureSelector, action: closureSelector.selector, for: controlEvents) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment