0

The standard way to respond to a UIButton tap, is:

  1. Statically link a method and tap event with IBAction.
  2. Use a UITapGestureRecognizer, specifying target and action(a selector).

I want the event handlers to be swift block/closure, they are more flexible (no specific target/action), and allows reconfiguration.

Is there a way to do this without jumping through the hoops of target/actions?

I am using Swift 3, by the way.

And I have read this Question, which uses a private method: Gesture Recognizers and Blocks

NeoWang
  • 17,361
  • 24
  • 78
  • 126
  • Thanks. I guess I didn't search with the right keywords, SO should support semantic keyword match... – NeoWang Oct 04 '17 at 18:01

1 Answers1

3

You could create your own button subclass which wraps the selector syntax around a closure-based API.

class MyButton: UIButton {

    var action: (() -> ())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }

    private func sharedInit() {
        addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
    }

    @objc private func touchUpInside() {
        action?()
    }

}

Then to add an action to the button, you can just set the closure.

let button = MyButton()
button.action = {
    print("hello")
}
nathangitter
  • 9,607
  • 3
  • 33
  • 42