Skip to content

Instantly share code, notes, and snippets.

@loganmoseley
Created November 21, 2017 22:20
Show Gist options
  • Save loganmoseley/0c40794e587132c3bdb9da32a2cbd846 to your computer and use it in GitHub Desktop.
Save loganmoseley/0c40794e587132c3bdb9da32a2cbd846 to your computer and use it in GitHub Desktop.
Add a block as the touchUpInside handler.
import UIKit
public extension UIButton {
public typealias TouchUpInside = () -> Void
public func setTouchUpInside(_ block: @escaping TouchUpInside) {
touchUpInsideBlock = block
addTarget(self, action: #selector(runTouchUpInside), for: .touchUpInside)
}
@objc private func runTouchUpInside() {
touchUpInsideBlock?()
}
private var touchUpInsideBlock: TouchUpInside? {
get {
objc_sync_enter(self); defer { objc_sync_exit(self) }
return objc_getAssociatedObject(self, &AssociatedKeys.targetBlockKey) as? TouchUpInside
}
set {
objc_sync_enter(self); defer { objc_sync_exit(self) }
objc_setAssociatedObject(self, &AssociatedKeys.targetBlockKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
private struct AssociatedKeys {
static var targetBlockKey = "targetBlockKey"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment