SwiftUI PKCanvasView in a .sheet hides/dismisses tools when dismiss is triggered

120 Views Asked by At

I have a DrawingView which is presented inside a .sheet in SwiftUI:

...
.sheet { DrawingView() }
struct DrawingView: View {
    private var canvasView = PKCanvasView()
    @Environment(\.dismiss) var dismiss

    var body: some View {
        NavigationStack {
            GeometryReader { proxy in
                MyCanvas(canvasView: canvasView)
            }
...

That view hosts my PKCanvasView:

struct MyCanvas: UIViewRepresentable {
    var canvasView: PKCanvasView
    @Binding var oldImage: UIImage?
    let picker = PKToolPicker()

    func makeUIView(context: Context) -> PKCanvasView {
        self.canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
        self.canvasView.becomeFirstResponder()
        return canvasView
    }
    
    func updateUIView(_ uiView: PKCanvasView, context: Context) {
        print(#function, uiView.drawing.strokes.count)
        picker.addObserver(canvasView)
        picker.setVisible(true, forFirstResponder: uiView)
        DispatchQueue.main.async {
            uiView.becomeFirstResponder()
        }
    }
}

So far so good, but when I start to dismiss the sheet the PKView automatically dismisses the tools. When I then swipe the sheet back up they're gone. I can still paint with the last selected pen, but that's it. I assume it's a first responder issue? That SwiftUI tells the PKCanvasView to remove the responder, and it therefore dismisses the tools, right? Similar similar to the keyboard being dismissed: (see this post)

1

There are 1 best solutions below

1
vitaminhvn On

Maybe you can use canvasView.becomeFirstResponder() and canvasView.resignFirstResponder() manually to handle with it