swiftswiftuiios-pdfkit

How to set PDFPageOverlayViewProvider for PDFView?


[UPDATED] I'm trying to set a pageOverlayViewProvider for a PDFView and it does not work as expected. PDFPageOverlayViewProvider methods are not being called, PDFViewDelegate methods are working fine.

struct ReaderView: UIViewRepresentable {
    
    public typealias UIViewType = PDFView
    
    let url: URL
    let document: PDFDocument
    
    init(_ url: URL) {
        self.url = url
        self.document = PDFDocument(url: self.url)!
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    func makeUIView(context: Context) -> PDFView {
        let pdfView = PDFView()
        
        pdfView.document = document
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical
        pdfView.autoScales = true
        pdfView.delegate = context.coordinator
        pdfView.pageOverlayViewProvider = context.coordinator
        pdfView.usePageViewController(true)
        pdfView.backgroundColor = .clear
        
        document.delegate = context.coordinator

        return pdfView
    }
    
    func updateUIView(_ uiView: PDFView, context: Context) {

    }
}
extension ReaderView {
    
    class Coordinator: NSObject, PDFPageOverlayViewProvider, PDFViewDelegate, PDFDocumentDelegate {
        
        func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
            return UIView(frame: .zero)
        }
        
        func pdfView(_ pdfView: PDFView, willDisplayOverlayView overlayView: UIView, for page: PDFPage) { 
        }
        
        func pdfView(_ pdfView: PDFView, willEndDisplayingOverlayView overlayView: UIView, for page: PDFPage) { 
        }
        
        func pdfViewWillClick(onLink sender: PDFView, with url: URL) {
        }
        
        func didMatchString(_ instance: PDFSelection) {
        }

}

Solution

  • To get pageOverlayViewProvider to work with PDFView, it seems that setting this instance property must be done before associating a PDF document with PDFView.

    In using UIViewRepresentable, the following ought to work when making the PDFView with the makeUIView function:

    func makeUIView(context: Context) -> PDFView {
        let pdfView = PDFView()
        
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical
        pdfView.autoScales = true
        pdfView.delegate = context.coordinator
        pdfView.pageOverlayViewProvider = context.coordinator
        pdfView.usePageViewController(true)
        pdfView.backgroundColor = .clear
        
        pdfView.document = document
        document.delegate = context.coordinator
    
        return pdfView
    }