Home > Software engineering >  How do I get the currently selected pencil kit color?
How do I get the currently selected pencil kit color?

Time:05-26

I have the following pencil kit setup:

class PencilKitVC: UIViewController {

    // MARK: - Views

    private let canvasView = PKCanvasView()
    private let toolPicker = PKToolPicker()

    // MARK: - View Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
    }

    // MARK: - Setup

    private func setupViews() {
        view.backgroundColor = .lightGray

        canvasView.backgroundColor = .white
        // Support finger and pencil
        canvasView.drawingPolicy = .anyInput

        view.addSubview(canvasView)
        canvasView.snp.makeConstraints {
            $0.leading.trailing.top.equalToSuperview().inset(16.0)
            $0.bottom.equalTo(view.safeAreaLayoutGuide).inset(16.0)
        }

        canvasView.minimumZoomScale = 0.5
        canvasView.maximumZoomScale = 4.0

        toolPicker.setVisible(true, forFirstResponder: canvasView)
        toolPicker.addObserver(canvasView)
        canvasView.becomeFirstResponder()
    }

}

Is it possible to get the currently selected color in the PKToolPicker via code? I need this color so I can use it on a text field feature I am adding.

CodePudding user response:

You need to add an observer to ToolPicker. Then listen to it.

toolPicker.addObserver(self)

func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
    if let inkingTool = toolPicker.selectedTool as? PKInkingTool {
        let color = inkingTool.color
    }
}

You can get more info from official doc:- here.

  • Related