Swift: Closure based actions

Payal Kandlur
1 min readFeb 21, 2022

--

The iOS 14 SDK introduced many improvements and new APIs that allow developers to write efficient code.

The target-action pattern is used in combination with user interface controls as a callback to a user event. Whenever a button is pressed on a target, its action will be called.

One such example is the API which is a closure based action API instead of the addTarget method in UIControls. We can write a closure based code using the action handler. Let’s dive into the code.

What we usually do:

func setupUI() {
let button = UIButton(type: .system)
self.view.addSubview(button)
button.setTitleColor(.systemBlue, for: .normal)
button.setTitle("Tap me", for: .normal)
button.frame = CGRect(x:0,y:0,width:view.frame.width,height:50)
button.center = view.center
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}@objc func buttonTapped() {
print("Button tapped!")
}

The buttonTapped method will be called every time the button is tapped.

This can now be written as:

func setupUI() {
let button = UIButton(type: .system)
self.view.addSubview(button)
button.setTitleColor(.systemBlue, for: .normal)
button.setTitle("Tap me", for: .normal)
button.frame = CGRect(x:0,y:0,width:view.frame.width,height:50)
button.center = view.center
button.addAction(UIAction(handler: { [weak self] _ in
print("Button tapped")
}), for: .touchUpInside)
}

Here the action and the control definition are closer. The action handler is specified after the initialization of the button.

But…

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. And this can also make your code less readable.

That’s all!😊 Drop in your thoughts and suggestions in the comment section!

--

--

No responses yet