Passing a closure to a UIButton
I'm tired of @objc
#selector (nonsense: )
muddying up my Swift code. This most commonly rears its 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.)
- 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.