Using Action Closures with UIKit Controls

Gabriel Theodoropoulos
5 min readSep 24, 2021
Photo by Kelly Sikkema on Unsplash

When talking about user interface implementation on iOS, then SwiftUI is the framework that comes in everyone’s mind nowadays. SwiftUI gains more developers day by day, and gets improved with new features and possibilities year by year. However, this does not mean that UIKit framework belongs to the past yet; on the contrary, UIKit is, and will keep being around for a big part of the foreseeable future.

So, in every WWDC, besides all the news about SwiftUI that make us all get excited, there are also announcements and improvements that regard UIKit. And such a UIKit new feature is what this post deals with today.

Originally presented in WWDC 2020 along with iOS 14, UIKit makes it possible to just avoid using our familiar for years target-action pattern; the one that requires to specify a selector method to be invoked when a user interacts with a UIKit control. Instead, we may use closures, and therefore keep a control’s action together with its initialization and configuration.

The following few examples will make totally clear what exactly I am talking about. And if you have not been aware of this technique, then I bet that you are going to find it pretty interesting after having read this post.

The target-action pattern

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev