[英]Update inputAccessoryView in SwiftUI (UIViewRepresentable)
[英]Refreshing PDFViewer on SwiftUI UIViewRepresentable
我創建了一個 SwiftUI 包裝器,用於創建和顯示 PDF。 我有幾個功能,output 和新的 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)
}
}
您可以嘗試類似這種方法的非常簡單的方法,即使數據更改也不刷新視圖:
@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
中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.