我想在iPad OS 16中使用新的PDFKit OverlayProvider协议在PDFView上自动覆盖铅笔套件画布。我为PDFKit添加了PKCanvas视图作为OverlayView的子视图,这是UIView。我成功地显示和删除基于OverlayViewProvider协议的覆盖视图。在overlay provider中设置pdfview
画布按预期显示,然而,铅笔交互未激活。相反,只有PDF UI滚动视图手势被激活。我应该删除PDF视图的手势吗?
PDFView for Swift UI
struct PDFKitViewRepresentable: UIViewRepresentable {
let pdfDocument: PDFDocument
let pdfView:PDFView
init(showing pdfDoc: PDFDocument, pdfView:PDFView) {
self.pdfDocument = pdfDoc
self.pdfView = pdfView
}
func makeUIView(context: Context) -> PDFView {
pdfView.displayDirection = .vertical
pdfView.displayMode = .singlePageContinuous
pdfView.usePageViewController(true)
pdfView.pageBreakMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
pdfView.autoScales = false
pdfView.delegate = context.coordinator
pdfView.pageOverlayViewProvider = context.coordinator
pdfView.backgroundColor = UIColor(white: 0.04, alpha: 0.2)
return pdfView
}
func updateUIView(_ pdfView: PDFView, context: Context) {
pdfView.document = pdfDocument
}
func makeCoordinator()-> Coordinator {
Coordinator()
}
}
协调员代码
class Coordinator: NSObject, PDFPageOverlayViewProvider, PDFViewDelegate, PDFDocumentDelegate, UIGestureRecognizerDelegate, PKCanvasViewDelegate, PKToolPickerObserver {
var pageToViewMapping = [PDFPage: CustomUIView]()
func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
var resultView:CustomUIView = CustomUIView()
if let overlayView = pageToViewMapping[page] {
var canvas = overlayView.viewWithTag((Int(page.label!)!))
canvas?.becomeFirstResponder()
resultView = overlayView
} else {
let toolPicker = PKToolPicker.init()
var canvasView = PKCanvasView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
resultView.backgroundColor = UIColor.red.withAlphaComponent(0.1)
canvasView.drawingPolicy = .anyInput
canvasView.backgroundColor = .yellow.withAlphaComponent(0.2)
resultView.frame = page.bounds(for: .mediaBox)
toolPicker.addObserver(canvasView)
toolPicker.setVisible(true, forFirstResponder: canvasView)
canvasView.delegate = resultView
canvasView.becomeFirstResponder()
canvasView.tag = Int(page.label!)!
resultView.addSubview(canvasView)
pageToViewMapping[page] = resultView
}
let page = MyPDFPage(page:page)
return resultView
}
func pdfView(_ pdfView: PDFView, willDisplayOverlayView overlayView: UIView, for page: PDFPage){
// Overlay view will display
}
func pdfView(_ pdfView: PDFView, willEndDisplayingOverlayView overlayView: UIView, for page: PDFPage){
// Overlay view would be disappear
}
}
在2022年WWDC PDFKit视频中- https://developer.apple.com/videos/play/wwdc2022/10089/-它可以用不到30行代码实现。因此,我使用代码片段并检查基本机制。但不能在画布上画。
绘制手势和滚动手势发生冲突的原因是PDF视图的配置。
pdfView。displayMode = . singlepagcontinuouspdfView.usePageViewController (false)
那么你应该设置isUserInteractionEnabled为true在覆盖视图安装。
见PDFKit - PDFPageOverlayViewProvider与PKCanvasView不转发触摸事件- WWDC22 Session 10089
您还需要将PDFView
实例上的isInMarkupMode
设置为true
,因此它改变了命中测试的工作方式。