I am trying to integrate the PKCanvasView to a React Native app but when I try to add the canvasView
as a subView it doesn't show. It only works if I return it directly.
Here is my code.
// BBNativePencilManager.swift
// import PencilKit;
@objc(BBNativePencilManager)
class BBNativePencilManager: RCTViewManager {
override func view() -> UIView {
// let canvasView = PKCanvasView();
// let drawing = PKDrawing()
// canvasView.drawing = drawing;
// if #available(iOS 14.0, *) {
// canvasView.drawingPolicy = .anyInput
// }
// if (theme == "dark") {
// canvasView.overrideUserInterfaceStyle = .dark;
// } else {
// canvasView.overrideUserInterfaceStyle = .light;
// }
// canvasView.isOpaque = false;
// canvasView.backgroundColor = .clear;
// canvasView.isMultipleTouchEnabled = true;
// canvasView.backgroundColor = .yellow
// canvasView.tool = PKInkingTool(.pen, color: UIColor.black, width: 5)
// canvasView.becomeFirstResponder()
// return canvasView;
// The above code works correctly
return BBNativePencilView(); // <-- this does not work
}
override static func requiresMainQueueSetup() -> Bool {
return true
}
}
And the BBNativePencilView
// BBNativePencilView.swift
import UIKit
import PencilKit
class BBNativePencilView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(canvas)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var canvas: PKCanvasView = {
let canvasView = PKCanvasView()
let drawing = PKDrawing.init()
canvasView.drawing = drawing;
if #available(iOS 14.0, *) {
canvasView.drawingPolicy = .anyInput
}
canvasView.isOpaque = false;
canvasView.backgroundColor = .clear;
canvasView.isMultipleTouchEnabled = true;
canvasView.backgroundColor = .yellow
canvasView.tool = PKInkingTool(.pen, color: UIColor.black, width: 5)
canvasView.becomeFirstResponder()
return canvasView;
}()
}
Could someone explain the issue to me? Thank you!
This might be due to layout or frame issues when adding it as a subview. Ensure that the BBNativePencilView frame and the canvas frame are properly set. The canvas may not be visible if its frame is incorrectly set or too small.
override init(frame: CGRect) {
super.init(frame: frame)
canvas.frame = self.bounds;
canvas.autoresizingMask = [.flexibleWidth, .flexibleHeight];
self.addSubview(canvas);
}