我有这个代码,显示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")!
}
}
}
}
}
1条答案
按热度按时间twh00eeo1#
您需要更新
updateUIView
函数中的必要代码。您可以进一步简化代码: