I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, ac
The associatedObject and wrapping and pointers and import of ObjectiveC are unnecessary, at least in Swift 3. This works great and is much more Swift-y. Feel free to throw a typealias in there for () -> () if you find it more readable, bit I find it easier to read the block signature directly.
import UIKit
class BlockButton: UIButton {
fileprivate var onAction: (() -> ())?
func addClosure(_ closure: @escaping () -> (), for control: UIControlEvents) {
self.addTarget(self, action: #selector(actionHandler), for: control)
self.onAction = closure
}
dynamic fileprivate func actionHandler() {
onAction?()
}
}