By Michael Behan

Hi πŸ‘‹, this is my personal site where I blog about iOS app development and related topics.

Passing a closure to a UIButton

01 Nov 2018 »

I’m tired of @objc #selector (nonsense: ) muddying up my Swift code. This most commonly rears it’s ugly head when dealing with buttons. Why can’t we just provide a button with a closure to execute when someone taps it? 1

// 😩
button.addTarget(self, action: #selector(myButtonHandler), for: .touchUpInside)

// 😍
button.on(.touchUpInside){
   ...
}

Well now you can! I made a small UIButton subclass that provides a swifty facade for adding target/actions for events and otherwise behaves exactly like a regular old UIButton (to be clear, selectors are still doing the business under the hood.)

Full source on gist.


  1. The reasons are simple and boring and because we're still working with Objective-C frameworks from the 1890s (that for the record, I still love), but that wasn't the point of this post.
© Michael Behan

By Michael Behan

Hi πŸ‘‹, this is my personal site where I blog about iOS app development and related topics.

© Michael Behan