UIButton: set closure for a specific UIControl event

How to set closure for the control event without using target and action?

Arkhyp Koshel
2 min readJun 16, 2021

Any self-respecting programmer strives to maximize his productivity. We can create templates or code snippets, but usually, they need to be improved to solve a specific problem. Another option is to create syntactic sugar for yourself, which does not affect the program’s behavior but makes the language more convenient. This approach can increase our productivity during routine tasks.

One good example in UIKit is adding an action to pass a target, selector, and event type. The following code snippet shows you how add target to UIButton object in a familiar way:

SomeView.swift file

As you can see, every time you add an action to a specific event, you need to add a separate obj-c method to handle it. This approach is not always appropriate and requires constantly adding new methods, especially if the processing of the event does not take in that view.
So if you want to use a closure instead of a selector, first of all, we need to create an ActionClosure class:

ActionClosure.swift file

ActionClosure class contains two properties selector and closure to execute. We set an associated value for a given object using a given key and association policy inside the init method. It will not release our ActionClosure object ahead of time.

The next step is to add an extension method to UIControl class, where we pass closure and the specific type of UI control event.

UIControl extension file

In the action method of UIControl, we create an ActionClosure object and pass it to self-object and closure. After all these changes, we can use a closure instead of a traditional target method. The following code snippet shows you how we use the action method.

Final SomeVIew class

Feel free to follow me, as we will discover more exciting stuff for iOS development!

Thank you for taking the time to read my story and for your support. If you enjoyed this article, please clap it to let me know. I will be sharing more stories in the future, so be sure to follow me to stay updated. Your feedback and support are greatly appreciated!
Follow Me: Twitter | LinkedIn

--

--

Arkhyp Koshel
Arkhyp Koshel

Written by Arkhyp Koshel

iOS and macOS developer. Passionated about technology, personal growth, and programming. Range of experiance the auto industry and banking.

No responses yet