swiftswiftuipkcanvasviewpktoolpicker

How to use PKCanvasView functionality without PKToolPicker?


I want to use PKCanvasView functionality without PKToolPicker. As soon as I set PKToolPicker visibility to false PKCanvasView draws noting.

What is the way to hide PKToolPicker and use PKCanvasView?

Here is the code which I am using:

struct DrawingView: View {
    private var canvasView = PKCanvasView()

    var body: some View {
        MyCanvas(canvasView: canvasView)
    }
}

struct MyCanvas: UIViewRepresentable {
    var canvasView: PKCanvasView
    let picker = PKToolPicker.init()

    func makeUIView(context: Context) -> PKCanvasView {
        self.canvasView.tool = PKInkingTool(.marker, color: .black, width: 1)
        self.canvasView.becomeFirstResponder()
        return canvasView
    }

    func updateUIView(_ uiView: PKCanvasView, context: Context) {
        picker.addObserver(canvasView)
        picker.setVisible(true, forFirstResponder: uiView)
        DispatchQueue.main.async {
            uiView.becomeFirstResponder()
        }
    }
}

enter image description here


Solution

  • You must specify the drawing policy if you do not use a PKToolPicker.

    Something like this:

    func makeUIView(context: Context) -> PKCanvasView {
        self.canvasView.tool = PKInkingTool(.marker, color: .black, width: 1)
        self.canvasView.drawingPolicy = .anyInput // Specify the drawing policy
        self.canvasView.becomeFirstResponder()
        return canvasView
    }