0

I have a basic app, a Main View with links to Drawing View. When I go to the Drawing View №1 and paint something with Apple Pencil, then go back to Main View, then go back to Drawing View №1 - I still see my painting. It stayed in the memory.

Question: What is a proper way to free the memory from PKCanvas and it's strokes when leaving the view?

I know I can "remove" the drawing by assigning canvasView.drawing = PKDrawing() a new blank drawing. But does it really solve the problem of keeping junk in the memory?

Here is my bare-minimum code:

import SwiftUI
import PencilKit

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack {
                NavigationLink(destination: DrawingView()) {
                    Text("Go to Drawing #1")
                }
                .padding()
                NavigationLink(destination: DrawingView()) {
                    Text("Go to Drawing #2")
                }
                .padding()
            }
        }
    }
}

struct DrawingView: View {
    @State private var canvasView = PKCanvasView()
    var body: some View {
        PKCanvasViewRepresentable(canvasView: $canvasView)
            .frame(width: 500, height: 500)
            .border(Color.blue)
    }
}
struct PKCanvasViewRepresentable: UIViewRepresentable {
    @Binding var canvasView: PKCanvasView
    
    func makeUIView(context: Context) -> PKCanvasView {
        canvasView.tool = PKInkingTool(.pen, color: .black, width: 26)
        canvasView.becomeFirstResponder()
        canvasView.delegate = context.coordinator
        
        return canvasView
    }

    func updateUIView(_ canvasView: PKCanvasView, context: Context) { }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, PKCanvasViewDelegate, UIPencilInteractionDelegate {
        var canvas: PKCanvasViewRepresentable
        
        init(_ canvas: PKCanvasViewRepresentable) {
            self.canvas = canvas
        }
        
        func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
            print("canvasViewDrawingDidChange()")
        }
    }
}
Stan
  • 77
  • 1
  • 7

0 Answers0