Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Last active December 21, 2017 11:51
Show Gist options
  • Save arashkashi/d461479282e6584c9074780918e0fdd4 to your computer and use it in GitHub Desktop.
Save arashkashi/d461479282e6584c9074780918e0fdd4 to your computer and use it in GitHub Desktop.
Functional Button
typealias UIButtonTargetClosure = (UIButton) -> ()
class ClosureWrapper: NSObject {
let closure: UIButtonTargetClosure
init(_ closure: @escaping UIButtonTargetClosure) {
self.closure = closure
}
}
extension UIButton {
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private var targetClosure: UIButtonTargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper else { return nil }
return closureWrapper.closure
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func addTargetClosure(closure: @escaping UIButtonTargetClosure) {
targetClosure = closure
addTarget(self, action: #selector(UIButton.closureAction), for: .touchUpInside)
}
@objc func closureAction() {
guard let targetClosure = targetClosure else { return }
targetClosure(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment