Typically, when using UIControl or UIButton, we add a selector as a callback action for when an event occurs on a button or control, such as the user pressing the button or touching the control.
For example, we would do the following:
When it comes to selector, the compiler only needs to know that it exists.. This can be done through a protocol and not be implemented.
For example, the following would crash your application:
This is because your application does NOT implement the onButtonPress function.
Now what if you could do all of this alongside the initialization of the button? What if you didn't have to specify callbacks and could instead specify blocks that can be added and removed at any time? Why worry about implementing selectors?
The above is a simple extension on UIControl. It adds an inner private class that has a callback func run(_ control: UIControl) that is used as the events' action.
Next we use object association to add and remove the target because it will not be retained by the UIControl.
The event handler function returns a Protocol in order to hide the inner workings of the Target class but also to allow you to enable and disable the target at any given time.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0