SwiftUI:如何显示PDF文件,然后将其更改为其他文件?

xriantvc  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(143)

我有这个代码,显示PDF,PDF加载良好。但是,我添加了一个工具栏按钮来将PDF更改为不同的文件,但它不起作用。我没有收到任何错误消息,但视图没有更新以显示新文件。

import SwiftUI
import PDFKit

struct PDFKitRepresentedView: UIViewRepresentable {
    let url: URL
    let pdfView = PDFView()
    
    init(_ url: URL) {
        self.url = url
        pdfView.document = PDFDocument(url: self.url)
    }

    func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
        return pdfView
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
    }
}

struct PDFKitView: View {
    var url: URL
    var body: some View {
        PDFKitRepresentedView(url)
    }
}

struct ContentView: View {
    
    @State var documentURL = Bundle.main.url(forResource: "file1", withExtension: "pdf")!
    
    var body: some View {
        
        NavigationStack {
            PDFKitView(url: documentURL)
            .toolbar {
                Button("Change PDF") {
                    documentURL = Bundle.main.url(forResource: "file2", withExtension: "pdf")!
                }
            }
        }
    }
}
twh00eeo

twh00eeo1#

您需要更新updateUIView函数中的必要代码。您可以进一步简化代码:

struct PDFKitRepresentedView: UIViewRepresentable {
    let url: URL

    init(_ url: URL) {
        self.url = url
    }

    func makeUIView(context: Context) -> PDFView {
        PDFView()
    }

    func updateUIView(_ uiView: PDFView, context: Context) {
        uiView.document = PDFDocument(url: url)
    }
}

相关问题