Learn how to detect and respond to touches from Apple Pencil.
UIKit reports touches from Apple Pencil in the same way it reports touches from the user’s fingers. Specifically, UIKit delivers a
UITouch object containing the location of the touch in your app. However, a touch object originating from Apple Pencil contains additional information, including the azimuth and altitude of Apple Pencil and the amount of force recorded at its tip.
Because Apple Pencil is a separate device, there is a delay between the time Apple Pencil gathers altitude, azimuth, and force values and the time that those values are reported to your app. As a result, UIKit may provide estimated values for those properties initially, and then provide the real values at a later time. If you use altitude, azimuth, or force information from Apple Pencil, you must explicitly handle estimated properties.
Handle Estimated Properties
When UIKit has only an estimate of a property's value, it includes a flag in the
estimated property of the corresponding
UITouch object. When handling a touch event, check that property to determine if you need to update the touch information later.
When a touch object contains estimated properties, UIKit also provides a value in the
estimation property that you can use to identify the touch later. Use the value in the
estimation property as a key to a dictionary that you maintain. Set the value of that key to the app-specific object that you use to store the touch information. When UIKit later reports the real values, use the index to look up your app-specific object and replace the estimated values with the real values.
Listing 1 shows the
add method of an app that captures touch data. For each touch, the method creates a custom
Stroke object with the touch information. If the force value of the touch is only an estimate, the
register method caches the sample in a dictionary using the value in the
estimation property as the key.
When UIKit receives the actual values for a touch, it calls the
touches method of your responder or gesture recognizer. Use that method to replace estimated data with the real values provided by UIKit.
Listing 2 shows an example of the
touches method, which updates the force value for the cached
Stroke objects created in Listing 1. The method uses the value in the
estimation property to retrieve the
Stroke object from the
estimates dictionary. It then updates the force value and removes the sample from the dictionary.