Lesson 21

Touches and Gestures

Your users interact with your iOS applications using touches and gestures, as opposed to a keyboard and mouse. While touches and gestures aren't the only ways users could interact with your apps, they are definitely the most common, with touches being more prevalent than gestures. Both touches and gestures are UIEvent instances and are managed by the UIApplication class.

Touch Events

When the user begins a touch sequence, the system generates a touch event and packages information into this event. A touch event is represented by an instance of the UIEventTypeTouches object; individual touches themselves are represented by UITouch instances.

Touch events are placed by UIKit in an application-level event queue and dispatched by your application's run loop to the window that initiated the event. From there they are forwarded to the first responder, which is usually the view where the touch occurred. If that view cannot handle the touch event, then the event is forwarded to the next responder in the chain, which could be the view controller that manages the view.

To place a UIView subclass at the front of the responder chain, you send it the becomeFirstResponder() message. Some views such as UITextView display a keyboard when they are sent this message.

If you want to process touch events in your own UIView subclass, you must first override canBecomeFirstResponder and return true from this method.

To handle touch events, you need to override one ...

Get Swift iOS 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.