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

如何使用UIDocumentPicker将PDF文件导入并存储到Table View Cell

解决PDF导入并关联Table View Cell的方案

咱们一步步来理清楚,确保导入的PDF能准确对应到Table View的单元格里:

首先,得先搞个数据模型来统一管理PDF的关键信息,不然零散的数据很容易乱。比如创建一个简单的PDFDocument类:

class PDFDocument {
    var fileName: String
    var fileURL: URL
    
    init(fileName: String, fileURL: URL) {
        self.fileName = fileName
        self.fileURL = fileURL
    }
}

接下来在你的ViewController里,声明一个数据源数组,用来存所有导入的PDF文件信息:

var pdfDocuments = [PDFDocument]()

然后调整addButtonTapped的逻辑——点击按钮时直接唤起文件选择器,让用户选PDF就行,不用先空插单元格:

@IBAction func addButtonTapped(_ sender: UIButton) {
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf])
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = false // 先默认选单个,后续可以改成多选
    present(documentPicker, animated: true)
}

接着实现UIDocumentPickerDelegate的方法,拿到选中的PDF后,把它存到沙盒(避免原URL后续无法访问),再更新数据源并刷新TableView:

extension YourViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let selectedURL = urls.first else { return }
        
        // 把PDF复制到App的沙盒目录,保证后续能正常访问
        let appDocDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let targetURL = appDocDir.appendingPathComponent(selectedURL.lastPathComponent)
        
        do {
            // 如果沙盒里已有同名文件,先删掉
            if FileManager.default.fileExists(atPath: targetURL.path) {
                try FileManager.default.removeItem(at: targetURL)
            }
            try FileManager.default.copyItem(at: selectedURL, to: targetURL)
            
            // 创建PDF模型,加到数据源数组
            let newPDF = PDFDocument(fileName: selectedURL.lastPathComponent, fileURL: targetURL)
            pdfDocuments.append(newPDF)
            
            // 刷新TableView,自动新增对应单元格(如果要动画效果,用insertRows替代reloadData)
            let newIndexPath = IndexPath(row: pdfDocuments.count - 1, section: 0)
            tableView.insertRows(at: [newIndexPath], with: .automatic)
        } catch {
            print("处理PDF文件出错:\(error.localizedDescription)")
        }
    }
}

最后处理TableView的数据源方法,让每个单元格对应数据源里的PDF模型:

extension YourViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return pdfDocuments.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath)
        let currentPDF = pdfDocuments[indexPath.row]
        cell.textLabel?.text = currentPDF.fileName // 单元格展示PDF文件名
        // 如果需要预览PDF,可以后续集成QLPreviewController或者自定义预览视图
        return cell
    }
}

哦对了,你之前写的insertNewFileTitle()其实可以不用单独写啦——因为我们是先拿到PDF数据,再把对应的模型加到数据源,最后让TableView自动生成对应单元格,这样天然就能保证数据和单元格一一对应,不会错位。

最后别忘了确认:你的ViewController已经遵守了UITableViewDataSource、UIDocumentPickerDelegate协议,TableView的单元格复用标识符也设置正确了哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:04:07