如何在SwiftUI中将PKToolPicker与PKCanvasView结合使用

时间:2020-09-23 00:33:12

标签: ios swift swiftui uiviewrepresentable pencilkit

当前,我能够拥有一个单独的PKCanvasView和一个PKToolPicker,当点击一个按钮时会显示它们。但是,该工具并未在选择器和画布视图之间转移。有谁知道如何链接两者,以便当我在选择器中更改工具时,该工具也在画布视图中更新?我在下面附加了我的代码。谢谢!

import SwiftUI
import PencilKit

struct DrawingView: View {
    @State private var showPicker = false
    @State private var canvasView = PKCanvasView()
    var body: some View {
        VStack {
            PencilKitView(isActive: $showPicker, canvasView: $canvasView)
            Button("Picker") { self.showPicker.toggle() }
        }
    }
}

struct PencilKitView: UIViewRepresentable {
    typealias UIViewType = PKCanvasView
    @Binding var isActive: Bool
    @Binding var canvasView: PKCanvasView

    let coordinator = Coordinator()
    
    class Coordinator: NSObject, PKToolPickerObserver {
        
        func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
            // some code
        }
        func toolPickerVisibilityDidChange(_ toolPicker: PKToolPicker) {
            // some code
        }
        
    }
    
    func makeCoordinator() -> PencilKitView.Coordinator {
        return Coordinator()
    }
    
    func makeUIView(context: Context) -> PKCanvasView {
        canvasView
    }
    
    func updateUIView(_ uiView: PKCanvasView, context: Context) {
        uiView.isOpaque = true
        uiView.becomeFirstResponder()

        let toolPicker = PKToolPicker.init()
        toolPicker.addObserver(uiView)
        toolPicker.addObserver(coordinator)
        toolPicker.setVisible(isActive, forFirstResponder: uiView)
        
        DispatchQueue.main.async {
            uiView.becomeFirstResponder()
        }
    }
}

1 个答案:

答案 0 :(得分:1)

解决了!

import SwiftUI
import PencilKit

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(.pen, color: .black, width: 15)
        self.canvasView.becomeFirstResponder()
        return canvasView
    }
    
    func updateUIView(_ uiView: PKCanvasView, context: Context) {
        picker.addObserver(canvasView)
        picker.setVisible(true, forFirstResponder: uiView)
        DispatchQueue.main.async {
            uiView.becomeFirstResponder()
        }
    }
}