UIAction

Pratik Sodha
1 min readSep 26, 2020

--

New way to handle an UIControl event using the completion block.

In iOS13 UIKit introduce UIAction to make sharing event handling code easier. Earlier UIAction usage limited as UIMenu element action closure.

From iOS14, Apple expands UIAction API for UIControl and UIBarButtonItem. UIControl comes up with new convenience init method which takes one action as a parameter. For BarButtonItem also available init method which accepts action.

//Initializer method of UIControlconvenience init(frame: CGRect, primaryAction: UIAction?)

primary action available for such controls which are inherited from UIControl. Like UIButton, UITextFiled, UISwitch, UIPageControl, UIStepper.

Let's dive into some code

Getting a reference to the control sender.

let switchButton = UISwitch()switchButton.addAction(UIAction(handler: { (action) in   guard let _switch = action.sender as? UISwitch else  {       return   }   print("Status : \(_switch.isOn)")}), for: .valueChanged)

Using many action closures can make code less readable and should only be used if the control callback logic can be written in a few lines of code. Otherwise, it’s better to use the old fashioned target-action pattern.

--

--

Pratik Sodha

Software developer at Spaceo Technologies. Loves to create iOS apps. Github : https://github.com/Pratik-Sodha