Skip to content

Instantly share code, notes, and snippets.

@nashfive
Last active March 29, 2018 19:23
Show Gist options
  • Save nashfive/7cb6c4663e531bbcd7b69624d319bf01 to your computer and use it in GitHub Desktop.
Save nashfive/7cb6c4663e531bbcd7b69624d319bf01 to your computer and use it in GitHub Desktop.
Add a tap closure on UIButton
import UIKit
extension UIButton {
private struct Handlers {
static var touchUpInside = "touchUpInside"
}
public func tap(_ closure: @escaping (UIButton) -> Void) {
objc_setAssociatedObject(self, &Handlers.touchUpInside, closure, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
addTarget(self, action: #selector(_touchUpInside), for: .touchUpInside)
}
@objc private func _touchUpInside() {
let sel = objc_getAssociatedObject(self, &Handlers.touchUpInside) as? ((UIButton) -> Void)
sel?(self)
}
}
// Usage
let button = UIButton(type: .system)
button.tap { button in
// WARNING: [unowned self] might be necessary since this closure is retained
print("tapped!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment