DemoCode:
import SwiftUI
import UIKit
import PencilKit
class PencilKitViewController: UIViewController, PKCanvasViewDelegate, PKToolPickerObserver {
lazy var canvasView: PKCanvasView = {
let canvasView = PKCanvasView()
canvasView.drawingPolicy = .anyInput
canvasView.translatesAutoresizingMaskIntoConstraints = false
return canvasView
}()
lazy var toolPicker: PKToolPicker = {
let toolPicker = PKToolPicker()
toolPicker.showsDrawingPolicyControls = true
toolPicker.addObserver(self)
return toolPicker
}()
let drawing = PKDrawing()
override func viewDidLoad() {
super.viewDidLoad()
canvasView.drawing = drawing
canvasView.delegate = self
view.addSubview(canvasView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
canvasView.frame = view.bounds
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
toolPicker.setVisible(true, forFirstResponder: canvasView)
toolPicker.addObserver(canvasView)
canvasView.becomeFirstResponder()
}
// canvas
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
print("drawing")
}
func canvasViewDidFinishRendering(_ canvasView: PKCanvasView) {
}
func canvasViewDidEndUsingTool(_ canvasView: PKCanvasView) {
}
func canvasViewDidBeginUsingTool(_ canvasView: PKCanvasView) {
}
}
// UIRepresentable for SwiftUI
struct PencilKitView: UIViewControllerRepresentable {
class Coordinator {
var parentObserver: NSKeyValueObservation?
}
var onSubmit: ((UIImage?, Error?) -> Void)? = .none
func makeUIViewController(context: Context) -> PencilKitViewController {
let pencilKitViewController = PencilKitViewController()
context.coordinator.parentObserver = pencilKitViewController.observe(\.parent, changeHandler: { vc, _ in
})
return pencilKitViewController
}
func updateUIViewController(_ uiViewController: PencilKitViewController, context: Context) {
}
func makeCoordinator() -> Self.Coordinator { Coordinator() }
}
struct ContentView: View {
var onSubmit: ((UIImage?, Error?) -> Void)? = .none
var body: some View {
PencilKitView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
iOS:
macCatalyst:
Post
Replies
Boosts
Views
Activity
I create a demo document app using document app template:
and I run build to preview the app:
There is two back buttons in navigation bar.
I also cannot find way to hide navigation back button in an document app.