swift 如何为PDFView设置PDFPageOverlayViewProvider?

mzillmmw  于 2023-09-30  发布在  Swift
关注(0)|答案(2)|浏览(132)

[已更新]我正在尝试为PDFView设置pageOverlayViewProvider,但它无法按预期工作。未调用PDFPageOverlayViewProvider方法,PDFViewDelegate方法工作正常。

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) {
        }

}
rekjcdws

rekjcdws1#

要让pageOverlayViewProviderPDFView一起工作,似乎必须在将PDF文档与PDFView关联之前 * 设置此示例属性。
在使用UIViewRepresentable时,在使用makeUIView函数制作PDFView时,以下应该可以工作:

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
}
mnemlml8

mnemlml82#

我也遇到过这个问题,基于omar的回答,我在PDFView子类中添加了以下内容:

private var _document: PDFDocument?
    
public override var pageOverlayViewProvider: PDFPageOverlayViewProvider? {
    willSet {
        // https://stackoverflow.com/questions/74281656
        _document = document
        document = nil
    }
    didSet {
        document = _document
    }
}

相关问题