You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift PDFKit实现PDF选择器:动态切换资源PDF问题求助

问题描述

我当前使用以下代码展示资源包中的PDF文档,但希望实现从列表选择PDF名称来替换固定的"Lipsum"资源。尝试通过NavigationLink传递字符串变量时遇到问题,PDF视图无法接受该变量,恳请提供解决方案。

import SwiftUI
import UIKit
import PDFKit


struct DocView: View {
    let pdfDoc: PDFDocument

 init() {
        let url = Bundle.main.url(forResource:"Lipsum", withExtension: "pdf")!
        pdfDoc = PDFDocument(url: url)!
    }
    
    var body: some View {
        PDFKitView(showing: pdfDoc)
    }
}

struct DocView_Preview: PreviewProvider {
    static var previews: some View {
        DocView()
    }
}


struct PDFKitView: UIViewRepresentable {
    
    let pdfDocument: PDFDocument
    
    init(showing pdfDoc: PDFDocument) {
        self.pdfDocument = pdfDoc
    }
    
    //you could also have inits that take a URL or Data
    
    func makeUIView(context: Context) -> PDFView {
        let pdfView = PDFView()
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        return pdfView
    }
    
    func updateUIView(_ pdfView: PDFView, context: Context) {
        pdfView.document = pdfDocument
    }
}
解决方案

要实现通过列表选择PDF并传递名称到DocView,核心是修改DocView的初始化逻辑,让它接收外部传入的PDF名称参数,而非硬编码固定值。以下是完整修改步骤:

1. 重构DocView,支持动态传入PDF名称

移除无参初始化方法,添加接收PDF名称的初始化逻辑,并增加错误处理避免崩溃:

struct DocView: View {
    let pdfDoc: PDFDocument?

    init(pdfName: String) {
        // 根据传入的名称查找资源包中的PDF
        if let url = Bundle.main.url(forResource: pdfName, withExtension: "pdf") {
            pdfDoc = PDFDocument(url: url)
        } else {
            pdfDoc = nil
        }
    }
    
    var body: some View {
        // 加载成功显示PDF,失败则提示错误
        if let doc = pdfDoc {
            PDFKitView(showing: doc)
        } else {
            Text("无法找到指定的PDF文件")
                .foregroundColor(.red)
                .padding()
        }
    }
}

2. 实现PDF列表选择视图

创建包含所有PDF名称的列表,通过NavigationLink将选中的名称传递给DocView:

struct PDFListView: View {
    // 替换为你资源包中实际的PDF名称列表
    let pdfNames = ["Lipsum", "UserGuide", "ProductManual"]
    
    var body: some View {
        NavigationStack { // iOS 16+ 使用NavigationStack,iOS 15及以下用NavigationView
            List(pdfNames, id: \.self) { name in
                NavigationLink(destination: DocView(pdfName: name)) {
                    Text(name)
                }
            }
            .navigationTitle("选择PDF文档")
        }
    }
}

3. 更新预览(可选)

修改DocView的预览代码,传入具体的PDF名称:

struct DocView_Preview: PreviewProvider {
    static var previews: some View {
        DocView(pdfName: "Lipsum")
    }
}

关键说明

  • 核心改动是将DocView的硬编码PDF名称改为参数传入,让视图具备动态加载能力。
  • 增加错误处理逻辑,避免因资源不存在导致的运行时崩溃。
  • 使用NavigationStack/NavigationView实现页面跳转,确保字符串参数能正确传递到目标视图。

内容的提问来源于stack exchange,提问作者FelixKing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:27:45