Created
August 31, 2019 20:38
-
-
Save highthem/cb4cba5c911e8dfcb185f2de647d71f8 to your computer and use it in GitHub Desktop.
good bye addTarget with #selector and @objc methods :)
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 { | |
/// 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