Search code examples
iosswiftuikitios-pdfkitpencilkit

PDFKit - PDFPageOverlayViewProvider with PKCanvasView is not forwarding Touch events - WWDC22 Session 10089


I am trying to utilize the PDFPageOverlayViewProvider protocol of the PDFView class in the PDFKit framework introduced with iOS 16 in order to display a PencilKit PKCanvasView on top of a PDF document so that the user can draw stuff on the PDF.

What I am trying to accomplish is basically the same thing as shown in the WWDC22 Session 10089. Sadly, there is no sample code provided which includes this functionality.

Here is my problem: I manage to add the PKCanvasView to the view hierarchy via the PDFPageOverlayViewProvider protocol, but I can't draw anything. I debugged the touch events using this technique and it appears that the touches are forwarded to the PDFDocumentView, which is an internal subview of the PDFView and a parent of my PKCanvasView.

View hierarchy from Xcode View debugger

enter image description here

How can I make sure that touch events made with the Apple pencil are forwarded to the PKCanvasView without disabling the scrolling and panning functionality of the PDFView?


Solution

  • This is the solution: put this code in overlayprovider's pdfView func:

       if (view.documentView != nil){
           for sv in view.documentView!.subviews {
               if (sv.theClassName == "PDFPageView" ){
                   sv.isUserInteractionEnabled = true
               }
           }
       } 
    

    For theClassName you should extend the NSObject like this:

    extension NSObject {
        var theClassName: String {
            return NSStringFromClass(type(of: self))
        }
    }