[英]How to implement PDF Viewer to SwiftUI application?
我正在構建一個顯示 PDF 的應用程序,但我不知道如何使用 SwiftUI 顯示 PDF 文件。 我找到了關於如何使用 UIKit 顯示 PDF 文件的教程,但是沒有關於 SwiftUI 的教程。 誰能幫我?
我也在嘗試使用 MVVM 設計模式來做到這一點。 如果有人可以幫助我,我將非常感激!
import SwiftUI
struct HomeView: View {
var deeds: [Deed] = deedsData
var body: some View {
NavigationView {
List(deeds) { item in
Button(action: {
}) {
HStack {
Image(systemName: "doc.fill")
Text(item.title)
}
}
}
.navigationTitle("title")
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView(deeds: deedsData)
}
}
import SwiftUI
struct Deed: Identifiable {
var id = UUID()
var title: String
var URL: String
}
let deedsData: [Deed] = [
Deed(title: NSLocalizedString("civilCode", comment: "Civil code"), URL: "https://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU19640160093/U/D19640093Lj.pdf"),
Deed(title: NSLocalizedString("penalCode", comment: "Penal code"), URL: "https://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU19970880553/U/D19970553Lj.pdf"),
Deed(title: NSLocalizedString("civilProcedureCode", comment: "Code of civil procedure"), URL: "https://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU19640430296/U/D19640296Lj.pdf"),
Deed(title: NSLocalizedString("familyAndGuardianshipCode", comment: "Family and guardianship code"), URL: "http://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU19640090059/U/D19640059Lj.pdf"),
Deed(title: NSLocalizedString("laborCode", comment: "Labor code"), URL: "https://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU19740240141/U/D19740141Lj.pdf"),
]
任何人都知道我怎么能在 MVVM 模式中做到這一點?
要使用僅限 Apple 的框架顯示 PDF,您需要通過 UIViewRepresentable 使用UIViewRepresentable
:
import PDFKit
import SwiftUI
struct PDFKitRepresentedView: UIViewRepresentable {
typealias UIViewType = PDFView
let data: Data
let singlePage: Bool
init(_ data: Data, singlePage: Bool = false) {
self.data = data
self.singlePage = singlePage
}
func makeUIView(context _: UIViewRepresentableContext<PDFKitRepresentedView>) -> UIViewType {
// Create a `PDFView` and set its `PDFDocument`.
let pdfView = PDFView()
pdfView.document = PDFDocument(data: data)
pdfView.autoScales = true
if singlePage {
pdfView.displayMode = .singlePage
}
return pdfView
}
func updateUIView(_ pdfView: UIViewType, context _: UIViewRepresentableContext<PDFKitRepresentedView>) {
pdfView.document = PDFDocument(data: data)
}
}
那么PDFKitRepresentedView
可以在您的視圖層次結構中使用。
這需要Data
object 作為輸入,因此您需要首先通過網絡調用將您必須的那些URL
對象轉換為Data
。 因此,您可能會執行以下操作:
@State var data : Data?
...
.onAppear {
self.data = try? Data(contentsOf: url)
}
請記住,這已大大簡化——您需要進行一些錯誤處理等。可能需要對 SwiftUI 網絡調用進行一些搜索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.