Skip to content

Instantly share code, notes, and snippets.

@BeauNouvelle
Last active July 9, 2019 14:18
Show Gist options
  • Save BeauNouvelle/08e591af267842bd03b97ca0825b24d8 to your computer and use it in GitHub Desktop.
Save BeauNouvelle/08e591af267842bd03b97ca0825b24d8 to your computer and use it in GitHub Desktop.
extension UIControl {
/// Typealias for UIControl closure.
public typealias UIControlTargetClosure = (UIControl) -> ()
private class UIControlClosureWrapper: NSObject {
let closure: UIControlTargetClosure
init(_ closure: @escaping UIControlTargetClosure) {
self.closure = closure
}
}
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private var targetClosure: UIControlTargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? UIControlClosureWrapper else { return nil }
return closureWrapper.closure
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, UIControlClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
@objc func closureAction() {
guard let targetClosure = targetClosure else { return }
targetClosure(self)
}
public func addAction(for event: UIControl.Event, closure: @escaping UIControlTargetClosure) {
targetClosure = closure
addTarget(self, action: #selector(UIControl.closureAction), for: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment