我已经创建了一个用于创建和显示PDF的SwiftUI包装器。我有两个功能,输出新的pdf作为数据。我有一个绑定到我的PDFViewer,但它并不像预期的那样工作。当我想要刷新视图时(例如,我添加了新文本,所以绑定数据发生了变化),而不调用“updateUIView”,就会遇到挑战。我想在不调用updateUIView的情况下解决这个问题,因为如果可能的话,我不想再次创建PDFDocument(data: data)。
我已经研究过代表,没有发现任何‘更新’或类似的功能。我还尝试了
struct PDFViewer: UIViewRepresentable {
typealias UIViewType = PDFView
@Binding var data: Data
@Binding var currentPageNumber: Int?
var pdfView: PDFView
let singlePage: Bool
init(pdfView: PDFView, data: Binding<Data>, singlePage: Bool = false, currentPage: Binding<Int?>) {
self.pdfView = pdfView
self._data = data
self.singlePage = singlePage
self._currentPageNumber = currentPage
}
func makeUIView(context: UIViewRepresentableContext<PDFViewer>) -> UIViewType {
pdfView.autoScales = true
if singlePage {
pdfView.displayMode = .singlePage
}
pdfView.delegate = context.coordinator
pdfView.document = PDFDocument(data: data) // <- DO NOT REFRESH EVEN IF DATA CHANGES
NotificationCenter.default.addObserver(forName: .PDFViewSelectionChanged, object: nil, queue: nil) { (notification) in
DispatchQueue.main.async {
let newPage = (pdfView.currentPage?.pageRef!.pageNumber)!
print(newPage)
if currentPageNumber != newPage {
currentPageNumber = newPage
}
}
}
return pdfView
}
func updateUIView(_ pdfView: UIViewType, context _: UIViewRepresentableContext<PDFViewer>) {
//// let newPDFDoc = PDFDocument(data: data) <---- DO NOT WANT TO CREATE IT AGAIN
// if pdfView.document?.dataRepresentation() != newPDFDoc?.dataRepresentation() {
//// pdfView.document = newPDFDoc
//// pdfView.go(to: pdfView.currentPage!)
// }
}
class Coordinator: NSObject, PDFViewDelegate, UIGestureRecognizerDelegate {
var parent: PDFViewer
init(_ parent: PDFViewer) {
self.parent = parent
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}发布于 2021-12-21 04:22:08
您可以尝试类似于这种方法的非常简单的方法,即使在数据更改时也不会刷新视图:
@State private var firstTimeOnly = true
....
func updateUIView(_ pdfView: UIViewType, context _: UIViewRepresentableContext<PDFViewer>) {
if self.firstTimeOnly {
self.firstTimeOnly = false
let newPDFDoc = PDFDocument(data: data) // <---- DO NOT WANT TO CREATE IT AGAIN
if pdfView.document?.dataRepresentation() != newPDFDoc?.dataRepresentation() {
pdfView.document = newPDFDoc
pdfView.go(to: pdfView.currentPage!)
}
}
}类似地,在makeUIView中。
https://stackoverflow.com/questions/70430526
复制相似问题