Detect and respond to double taps a user makes on Apple Pencil.
Framework
- UIKit
Overview
You can use Pencil interactions to allow users to access functionality in your app quickly. Double-tapping the Apple Pencil lets the user perform actions such as switching between drawing tools without moving the Pencil to another location on the screen.
Add a Pencil Interaction
To handle double taps from Apple Pencil in your app, create a UIPencil
object and set its delegate
to an object that implements the UIPencil
protocol. Finally, add the interaction to your app’s view, as in Listing 1.
Adding a Pencil interaction to a view
let pencilInteraction = UIPencilInteraction()
pencilInteraction.delegate = self
view.addInteraction(pencilInteraction)
Handle the Double Tap
The delegate receives the double tap event when the user double-taps their Pencil. It implements the pencil
method, which the system calls after the user double-taps the Apple Pencil.
In your implementation of this method, decide whether to perform the action selected by the user in the Settings app, or perform an alternative behavior that’s suitable for your app. When possible, perform the user’s preferred action.
Taking this step allows you to provide a consistent user experience across apps that support Pencil interactions. To check the user’s preferred action, use the preferred
class property on UIPencil
, as in Listing 2.
Switching drawing tools after double-tapping an Apple Pencil
func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {
if UIPencilInteraction.preferredTapAction == .switchPrevious {
leftRingControl.switchToPreviousTool()
}
}
Should you decide not to support the preferred action, provide an intuitive way to let the user know what will happen when they double-tap the Pencil, and give them the option to disable this action.