How it works
PencilPreferredAction is a set of constants that names the action a person has chosen for their Apple Pencil's double-tap gesture in System Settings. SwiftUI surfaces this preference so your app can honor it: when someone double-taps their Pencil, you can respond in the way they expect rather than guessing at a behavior. Reach for it when your drawing or annotation interface wants to participate in the system-wide Pencil gesture — for example, switching to the eraser or toggling between tools — and you want to express which action your view treats as preferred.
Declare the preferred action with preferredPencilDoubleTapAction(_:)
Attach this modifier to the view that owns the Pencil interaction to state which
PencilPreferredActionyour view favors for a double-tap. Here the view passes.switchEraser, one of the constants onPencilPreferredAction, declaring that a double-tap should move to the eraser. The modifier is applied after.padding()on theVStack, scoping the preference to that view's interactions.Choose the constant that matches your intent
PencilPreferredActionenumerates the standard gesture outcomes — values like.switchEraser,.switchPrevious,.showColorPalette, and.ignore— so you select the one your tool means rather than inventing custom semantics. The example uses.switchEraser; substituting a different case is how you change which preferred action the view advertises.Respond to the gesture with onPencilDoubleTap
Declaring a preferred action only states intent; you still react to the actual double-tap in
onPencilDoubleTap. Its closure receives the gesture value, letting you perform the work the preferred action implies. In the example the closure updatesstatusto"Switched tool", standing in for the real tool change you would make.Keep the declared action and the handler consistent
The constant you pass to
preferredPencilDoubleTapAction(.switchEraser)and the behavior you run insideonPencilDoubleTapshould describe the same outcome, so the gesture does what the person expects from their Pencil settings. Treat thePencilPreferredActionvalue as the contract and the handler as its implementation.
preferredPencilDoubleTapAction(.switchEraser) to preferredPencilDoubleTapAction(.showColorPalette) to advertise a different PencilPreferredAction and see how the declared preference shifts.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct PencilPreferredActionDemo: View {
@State private var status = "Double-tap your Apple Pencil"
var body: some View {
VStack(spacing: 16) {
Image(systemName: "applepencil")
.font(.largeTitle)
Text(status)
.font(.headline)
}
.padding()
.preferredPencilDoubleTapAction(.switchEraser)
.onPencilDoubleTap { value in
status = "Switched tool"
}
}
}