A Deep Dive into Swift’s Target-Action

Another design pattern

Photo by Foto Sushi on Unsplash

Prerequisites:

Terminology

Design Pattern: A solution to commonly occurring problem in software design

The problem to be solved

An object holds information that allows it to send information to another object when an even occurs.

The solution

An action selector identifies the method that will be invoked when an event occurs.

An example

If we were to create a UIPanGestureRecognizer in Playgrounds we might develop the following code

Click for Gist
UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
Click for Gist

Differences between UIKit and AppKit

UIKit (iOS) and AppKit (MacOS) both use the target-action design pattern. AppKit uses a control-cell architecture for most controls, where the control owns light-weight cell objects that hold the target and action properties for the control. The difference is subtle, but shouldn’t be too difficult for the more experienced developer!

Conclusion:

This article has covered quite a few topics. Since target-action is frequently used in iOS I hope this has been a good use of your time, running through what the pattern can be used for, how we can use selectors and create functions that have practical use in iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store