Replacing Selectors with Closures in UIButton

Replacing Selectors with Closures in UIButton

iOS 14.0 brings us many improvements and new APIs using which the developers can write efficient code. One such API is the closure based action API instead of the addTarget method in UIControls. Yes, you heard me right—no more usage of addTarget methods, #selector(), and @objc annotation in front of methods. More importantly, we can write a closure based code using the action handler. Okay, enough talk, let’s dive into the code.

Target-based UIButton. (iOS 13.0 and earlier)

Closure based UIButton (iOS 14.0 and later)

Variant 1

Variant 2

As you can see, I have mentioned two variants of closure based UIButton.

In the first variant, the action handler is specified during the initialization of the button. In the second variant, the action handler is specified after the initialization of the button. It is up to the developer to choose whichever method they want. My personal preference is the second variant.

Limitations

As I had mentioned earlier, the closure based actions are available for iOS 14.0 and above. If you want to support iOS 13.0 and earlier, you will still have to use the legacy addTarget method.

Closing thoughts

It is good to see that Apple is working so hard to improve its SDKs. Let us try to adopt the new APIs as much as we can to make the development process easier and effective. It will be challenging to adapt to the change, but it is worth it. You will see more about these new APIs in the upcoming articles, and I will show you how to make the most out of them.

Article originally posted at https://ohmyswift.com/blog/

App Showcase

We always want to give back to the community. So we decided that we will review some of the most amazing apps which we had used.

App name — Winya (iOS and iPad OS app)

A free screen-sharing app that casts your screen to Twitch in HD. It will be useful for gamers to streaming their gameplay to Twitch. Dear Readers, download the app and show them your support

iOS, and iPadOS download link

About the author

Support us

Like our articles? Support us here: https://www.buymeacoffee.com/ohmyswift

iOS Engineer @zoho , Creator — http://ohmyswift.com Support OhMySwift by buying us a pizza! 👉 https://buymeacoffee.com/ohmyswift

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store