Article

Handling Touches in Your View

Use touch events directly on a view subclass if touch handling is intricately linked to the view's content.

Overview

If you don't plan to use gesture recognizers with a custom view, you can handle touch events directly from the view itself. Because views are responders, they can handle Multi-Touch events and many other types of events. When UIKit determines that a touch event occurred in a view, it calls the view’s touchesBegan(_:with:), touchesMoved(_:with:), or touchesEnded(_:with:) method. You can override these methods in your custom views and use them to provide a response to touch events.

The methods you override in your views (or in any responder) to handle touches correspond to different phases of the touch event–handling process. For example, Figure 1 illustrates the different phases of a touch event. When a finger (or Apple Pencil) touches the screen, UIKit creates a UITouch object, sets the touch location to the appropriate point, and sets its phase property to UITouch.Phase.began. When the same finger moves around the screen, UIKit updates the touch location and changes the phase property of the touch object to UITouch.Phase.moved. When the user lifts the finger from the screen, UIKit changes the phase property to UITouch.Phase.ended and the touch sequence ends.

Figure 1

The phases of a touch event

A touch begins when the user's finger touches the screen. The system updates the touch when the user's finger moves or the touch parameters change. The touch ends when the user lifts the same finger from the screen. If an interruption such as an incoming call occurs, the system cancels any active touches.

Similarly, the system may cancel an ongoing touch sequence at any time; for example, when an incoming phone call interrupts the app. When it does, UIKit notifies your view by calling the touchesCancelled(_:with:) method. You use that method to perform any needed cleanup of your view’s data structures.

UIKit creates a new UITouch object for each new finger that touches the screen. The touches themselves are delivered with the current UIEvent object. UIKit distinguishes between touches originating from a finger and from Apple Pencil, and you can treat each of them differently.

Topics

Related Articles

Getting High-Fidelity Input with Coalesced Touches

Learn how to support high-precision touches in your app.

Minimizing Latency with Predicted Touches

Create a smooth and responsive drawing experience using UIKit's predictions for touch locations.

Implementing a Multitouch App

Learn how to create a simple app that handles Multitouch input.

See Also

Touches

Handling Input from Apple Pencil

Learn how to detect and respond to touches from Apple Pencil.

Tracking the Force of 3D Touch Events

Manipulate your content based on the force of touches.

class UITouch

An object representing the location, size, movement, and force of a touch occurring on the screen.