The problem
PencilKit gives you Apple’s own drawing engine, the same one Notes and Markup use, with pressure, tilt, the ruler, the lasso and the standard tool palette. It is also a UIKit framework with a first-responder-driven tool picker, and SwiftUI has no native canvas for it. Most “PencilKit in SwiftUI” bugs come from that gap: a tool picker that never appears, a drawing that resets when the view updates, or a squeeze that does nothing. This article builds the bridge properly, adds the Apple Pencil Pro interactions, and explains when PencilKit is the wrong tool.
What PencilKit gives you
The pieces you will use, with their minimum OS:
PKCanvasView(iOS 13): a scroll view subclass that captures strokes into aPKDrawing.PKDrawing(iOS 13): a value type holding strokes, withdataRepresentation()andinit(data:)for storage.PKToolPicker(iOS 13; the publicinit()arrived in iOS 14, replacing the oldershared(for:)window lookup).PKCanvasView.drawingPolicy(iOS 14): whether fingers draw, only Pencil draws, or the system default applies.PKToolPicker(toolItems:), custom tool items and an accessory button (iOS 18), shown in Apple’s sample Configuring the PencilKit tool picker.
The Apple Pencil interaction modifiers in SwiftUI, onPencilDoubleTap(perform:) and onPencilSqueeze(perform:), are iOS 17.5 and later. That is why this article’s platforms line starts there.
Step 1: wrap the canvas
Christine Abernathy’s Drawing with PencilKit: Getting Started at Kodeco set the pattern most tutorials still copy: a UIViewRepresentable with a coordinator that acts as the canvas delegate. Her version passed the canvas view itself around as a binding. I prefer to keep the UIKit view private to the representable and pass only the PKDrawing, which is a value your model can own, compare and save.
import SwiftUI
import PencilKit
struct DrawingCanvas: UIViewRepresentable {
@Binding var drawing: PKDrawing
var showsToolPicker: Bool
func makeCoordinator() -> Coordinator {
Coordinator(drawing: $drawing)
}
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.drawing = drawing
canvas.drawingPolicy = .default
canvas.backgroundColor = .clear
canvas.isOpaque = false
canvas.delegate = context.coordinator
context.coordinator.toolPicker.addObserver(canvas)
return canvas
}
func updateUIView(_ canvas: PKCanvasView, context: Context) {
context.coordinator.drawing = $drawing
if canvas.drawing != drawing {
canvas.drawing = drawing
}
let picker = context.coordinator.toolPicker
picker.setVisible(showsToolPicker, forFirstResponder: canvas)
if showsToolPicker {
canvas.becomeFirstResponder()
}
}
static func dismantleUIView(_ canvas: PKCanvasView, coordinator: Coordinator) {
coordinator.toolPicker.setVisible(false, forFirstResponder: canvas)
coordinator.toolPicker.removeObserver(canvas)
}
final class Coordinator: NSObject, PKCanvasViewDelegate {
var drawing: Binding<PKDrawing>
let toolPicker = PKToolPicker()
init(drawing: Binding<PKDrawing>) {
self.drawing = drawing
}
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
if drawing.wrappedValue != canvasView.drawing {
drawing.wrappedValue = canvasView.drawing
}
}
}
}
A few choices in there matter:
- One tool picker per canvas, owned by the coordinator. The picker must outlive individual updates, and the coordinator lives as long as the representable.
- The equality checks.
PKDrawingisEquatable. Without the checks, every stroke would write to the binding, SwiftUI would callupdateUIView, and you would assign the same drawing back, which is wasteful at best and resets in-progress state at worst. drawingPolicy = .default. The documentation says.defaultfollows the person’s pencil setting while the tool picker is visible and accepts only Apple Pencil otherwise.showsDrawingPolicyControls(iOS 14) controls whether the picker shows that setting. Abernathy used.anyInputunder#if targetEnvironment(simulator)so she could draw with the mouse. That is a good trick for development, as long as it stays out of release builds.dismantleUIView. It hides the picker and removes the observer when SwiftUI tears the view down. Without it, a floating palette can outlive the screen it belonged to.
The class conforms to PKCanvasViewDelegate, a main-actor UIKit protocol, so under Swift 6 the coordinator is main-actor isolated and the delegate callback needs no hopping.
Step 2: show the tool picker the way PencilKit expects
PKToolPicker does not attach to a view. It appears when a responder it is visible for becomes first responder. That explains the two calls in updateUIView: setVisible(_:forFirstResponder:) registers the canvas, and becomeFirstResponder() makes it current. If the picker never appears, check in this order:
- The canvas is in a window.
becomeFirstResponder()fails silently before that, which is why the call sits inupdateUIViewand not inmakeUIView. - Another responder, often a text field in a toolbar, has not taken first responder back.
- The picker is still referenced. A local
PKToolPicker()created insidemakeUIViewis deallocated straight away.
Using it from SwiftUI:
import SwiftUI
import PencilKit
@Observable
final class Sketch {
var drawing = PKDrawing()
var data: Data { drawing.dataRepresentation() }
func load(_ data: Data) throws {
drawing = try PKDrawing(data: data)
}
}
struct SketchScreen: View {
@State private var sketch = Sketch()
@State private var showsTools = true
var body: some View {
DrawingCanvas(drawing: $sketch.drawing, showsToolPicker: showsTools)
.ignoresSafeArea(.container, edges: .bottom)
.toolbar {
Button(showsTools ? "Hide Tools" : "Show Tools", systemImage: "pencil.tip.crop.circle") {
showsTools.toggle()
}
}
.navigationTitle("Sketch")
}
}
Save sketch.data wherever your document lives: a file, SwiftData, or a FileDocument. PKDrawing(data:) throws on corrupt or unsupported data. Surface that error to the user. Do not swap in an empty drawing silently, or the next autosave overwrites their work with nothing.
Step 3: customize the tool picker (iOS 18)
From iOS 18 you choose which tools appear and in what order. Apple’s sample adds a second pen with its own identifier, a custom stamp tool and an accessory button. The rules it spells out:
- Two system tools of the same type need different
identifiervalues, or the picker treats them as duplicates and shows only the first. - Custom tools use
PKToolPickerCustomItem.Configurationwith animageProviderclosure. PencilKit calls it again when color or width change. CallreloadImage()when your own attributes change. accessoryItemtakes aUIBarButtonItemfor a canvas action that is not a tool, such as inserting a signature.
The WWDC24 session Squeeze the most out of Apple Pencil adds two details. While a custom tool is selected, drawing on observing canvases is turned off, because your code does the rendering. The accessory button disappears when the picker is minimized, so the same action must exist elsewhere in your UI.
Build the picker in the coordinator’s initializer behind if #available(iOS 18, *) if your deployment target is lower, and fall back to PKToolPicker().
Step 4: double tap and squeeze
Second-generation Apple Pencil and Apple Pencil Pro support double tap. Only Apple Pencil Pro supports squeeze, and the first-generation Pencil supports neither, according to Apple’s Apple Pencil interactions overview.
Both have a system-wide preferred action that people set in Settings > Apple Pencil. Your app reads it from the environment (preferredPencilDoubleTapAction and preferredPencilSqueezeAction, iOS 17.5) and should honour it when it makes sense. PencilPreferredAction includes .ignore, .switchEraser, .switchPrevious, .showColorPalette, .showInkAttributes, .showContextualPalette and .runSystemShortcut.
import SwiftUI
enum DrawingTool: Hashable { case pen, marker, eraser, lasso }
struct ToolHost<Content: View>: View {
@Binding var tool: DrawingTool
@ViewBuilder var content: Content
@State private var previousTool: DrawingTool = .pen
@State private var showsPalette = false
@State private var paletteAnchor: PopoverAttachmentAnchor = .point(.center)
@Environment(\.preferredPencilDoubleTapAction) private var doubleTapAction
@Environment(\.preferredPencilSqueezeAction) private var squeezeAction
var body: some View {
content
.onPencilDoubleTap { _ in
perform(doubleTapAction, anchor: nil)
}
.onPencilSqueeze { phase in
guard case let .ended(value) = phase else { return }
perform(squeezeAction, anchor: value.hoverPose?.anchor)
}
.popover(isPresented: $showsPalette, attachmentAnchor: paletteAnchor) {
ToolPalette(tool: $tool)
}
}
private func perform(_ action: PencilPreferredAction, anchor: UnitPoint?) {
switch action {
case .switchEraser:
switchTo(tool == .eraser ? previousTool : .eraser)
case .switchPrevious:
switchTo(previousTool)
case .showContextualPalette:
paletteAnchor = .point(anchor ?? .center)
showsPalette = true
default:
break
}
}
private func switchTo(_ newTool: DrawingTool) {
(previousTool, tool) = (tool, newTool)
}
}
struct ToolPalette: View {
@Binding var tool: DrawingTool
var body: some View {
Picker("Tool", selection: $tool) {
Text("Pen").tag(DrawingTool.pen)
Text("Marker").tag(DrawingTool.marker)
Text("Eraser").tag(DrawingTool.eraser)
Text("Lasso").tag(DrawingTool.lasso)
}
.pickerStyle(.inline)
.padding()
}
}
The .ended phase is the one to act on. PencilSqueezeGesturePhase also has .active and .failed, and Apple’s squeeze article reacts only to .ended. The hover pose’s anchor is a UnitPoint in the view’s space, which is exactly what PopoverAttachmentAnchor.point takes, so the palette opens under the Pencil tip.
Points from the WWDC24 session worth knowing before you ship:
- If the person’s squeeze preference is to run a shortcut, your app never receives the squeeze.
- Squeeze then long-press gives an undo and redo slider in every app, even without PencilKit. Installing a
UIPencilInteractionwhose delegate handles squeeze suppresses it, so only do that when you replace it with something better. - Treat squeeze as one discrete action. Don’t build a squeeze-and-hold mode.
The session also notes that PencilKit uses the hover pose to position the tool picker when it opens from a squeeze. Add handlers like the one above when your app has tools of its own or a custom canvas, and test them next to a PKCanvasView with the picker showing so the two do not both react to one gesture.
Hover
Apple Pencil hover tells your app where the tip is before it touches the glass. Apple’s hover spotlight on Procreate gives the range (up to 12 mm above the display) and the best design advice I have read on it. Use hover to preview, never to commit. Don’t make one cursor fit every tool. Don’t build interactions that only work with the iPad resting on a desk.
PencilKit tools draw their own hover preview. For custom tools, Apple’s tool picker sample does three things. It checks UIPencilInteraction.prefersHoverToolPreview (iOS 17.5) to respect the user’s setting. It tracks the tip with a UIHoverGestureRecognizer, whose zOffset is iOS 16.1 and later. And it uses rollAngle (iOS 17.5, Apple Pencil Pro) to rotate the preview. That recognizer is UIKit, so add it to the view you return from your representable. The session’s advice on roll: use it as stroke input, not to drive controls, and combine it with azimuth so devices without roll still produce a sensible result.
When PencilKit is not enough
PencilKit is the right default for notes, markup, signatures and sketching. It stops fitting when you need your own brush engine, vector output you control, or a stroke model that is not PencilKit’s. Then you handle touches yourself, and three things in Apple’s Handling input from Apple Pencil decide whether your ink feels right:
- Coalesced touches. Apple Pencil reports at up to 240 Hz while UIKit delivers events around 60 Hz. Read
coalescedTouches(for:)(iOS 9) on every event or your curves turn into polylines. - Predicted touches.
predictedTouches(for:)(iOS 9) lets you draw a short tentative segment ahead of the real one and throw it away on the next event. That hides most of the perceived latency. - Estimated properties. Force, altitude and azimuth can arrive as estimates and be corrected later through
touchesEstimatedPropertiesUpdated(_:). Key your samples byestimationUpdateIndexand patch them when the real values come in.
Use preciseLocation(in:) instead of location(in:) for Pencil touches, and render incrementally, only the new segment, instead of redrawing the whole stroke each frame. None of this exists in SwiftUI gesture values, so a custom engine is a UIView subclass behind a representable.
Traps
- Picker visible on the wrong screen. Forgetting
dismantleUIViewleaves the palette floating after navigation. - Drawing resets on update. Assigning
canvas.drawingunconditionally inupdateUIViewfights the user’s in-progress stroke. - Finger drawing surprise.
.anyInputmakes palm and scroll gestures draw. Prefer.defaultand let people choose. - Rotating or resizing. In resizable iPadOS 26 windows the canvas changes size. A
PKDrawingis in canvas coordinates, so decide whether content scales with the window or keeps its size, and setcontentSizeand zoom accordingly. - Mac.
PKCanvasViewandPKToolPickerare available in Mac Catalyst, but mouse drawing is a different experience. Check it before advertising drawing on the Mac.
Checklist
| Task | API | Minimum OS |
|---|---|---|
| Canvas in SwiftUI | PKCanvasView in UIViewRepresentable |
iOS 13 |
| Drawing policy | drawingPolicy |
iOS 14 |
| Tool picker instance | PKToolPicker(), addObserver, setVisible(_:forFirstResponder:) |
iOS 14 |
| Custom tools and order | PKToolPicker(toolItems:), PKToolPickerCustomItem |
iOS 18 |
| Save and load | dataRepresentation(), PKDrawing(data:) |
iOS 13 |
| Double tap | onPencilDoubleTap, preferredPencilDoubleTapAction |
iOS 17.5 |
| Squeeze (Pencil Pro) | onPencilSqueeze, preferredPencilSqueezeAction |
iOS 17.5 |
| Hover preview | UIHoverGestureRecognizer.zOffset / prefersHoverToolPreview |
iOS 16.1 / 17.5 |
| Barrel roll | rollAngle |
iOS 17.5 |
| Custom ink fidelity | coalescedTouches(for:), predictedTouches(for:) |
iOS 9 |
Test on real hardware with the Pencil you claim to support. The Simulator draws with a mouse, has no pressure, no hover and no squeeze, and tells you nothing about latency.
Sources and further reading
- Configuring the PencilKit tool picker Apple Developer Documentation
- Handling squeezes from Apple Pencil Apple Developer Documentation
- Apple Pencil interactions Apple Developer Documentation
- Handling input from Apple Pencil Apple Developer Documentation
- Squeeze the most out of Apple Pencil (WWDC24) Apple, WWDC24
- Drawing with PencilKit: Getting Started Christine Abernathy, Kodeco
- Spotlight on: Apple Pencil hover Apple Developer News