Last active
July 9, 2019 14:18
-
-
Save BeauNouvelle/08e591af267842bd03b97ca0825b24d8 to your computer and use it in GitHub Desktop.
This file contains 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 { | |
/// 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