Add a closure as a target for UIButton and other controls in Swift

Tram Ho

The target-action pattern is used in conjunction with UI controls as a user event callback command. Whenever a button is clicked on a target, its action will be called. The fact that the method is undefined close to the control definition is sometimes considered a downside, and that’s why a lot of developers like us look for closure solutions based on sites like Stack Overflow. .

The iOS 14 SDK introduced new APIs that let us use UIControls in conjunction with closures. The popular UIControl elements are UIButton, UISegmentedControl, and UISwitch but there are many others that inherit from the UIControl object.All of those interface elements can now be used with this new API.

1. Use UIControl with closure callback

You are probably familiar with the following code snippet:

The buttonTapped (_:) method will be called every time the button is touched. The same code can now be written like this:

This keeps acting close to the control definition which can improve your code discovery.

2. Get reference to the control sender

Another difference in the above code is that our method has a reference to the sender. This can be useful in some cases when you want to know the on-premises controls called linked methods.

With a new closure-based API, you can use action arguments to access the sender. For example, when you want to read text from a text field:

3. Should we always use new API closures?

Now you might find it tempting to use closures everywhere. However, a control action can be easily developed in code, making your code harder to read. In those cases, you can go back to the old target-action pattern to let you use a particular method. Because methods in Swift are easier to read when your control action requires multiple lines of code.

4. Conclusion

Using multiple closures can easily make your code harder to read and should only be used if the control callback logic can be written in a few lines of code. If not, it is better to use the old target-action template.

So my post here is over. Hopefully, this will help you in coding more efficiently.

Thank you for watching the article.

Share the news now

Source : Viblo