Replacing Selectors with Closures in UIButton

Rizwan Ahmed
3 min readMar 12, 2021

--

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)

Target-based UIButton. (iOS 13.0 and earlier)

Closure based UIButton (iOS 14.0 and later)

Variant 1

UIButton with Closures (Variant 1)

Variant 2

UIButton with Closures (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

--

--

Rizwan Ahmed
Rizwan Ahmed

Written by Rizwan Ahmed

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

No responses yet