Member-only story
A Deep Dive into Swift’s Target-Action
Another design pattern
Target-Action is one of the design patterns you’ll come across coding in Swift. This short guide is here to explain what this pattern is used for, and is here to help you out.
Difficulty: Beginner | Easy | Normal | Challenging
Prerequisites:
- You can use gestures in a Single View Application, or use Gestures in the Playground to set up this project
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.
This is often used in buttons and sliders.
The solution
An action selector identifies the method that will be invoked when an event occurs.
A target is the object to recieve the message when an event occurs. This is typically a controller (as in a view controller).
An example
If we were to create a UIPanGestureRecognizer
in Playgrounds we might develop the following code