1

我正在尝试为 Mac(不是 IOS)制作一个 PDF 查看器来完成一项任务,但我什至不知道如何让 PDF 真正显示出来。我们必须使用 PDFView 和 Quartz。我在这个主题上看到的大多数教程都使用如下内容:

view.setDocument(pdf)

但是 swift 说 PDFView 没有成员 setDocument。我查看了这里的文档,唯一看起来像它可以工作的东西是 setCurrentSelection 所以我尝试了:

import Cocoa
import Quartz

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var PDFV: PDFView!


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        
        let fileURL:URL = (Bundle.main.url(forResource: "example", withExtension: "pdf")! as NSURL) as URL
        let pdfDocument:PDFDocument = PDFDocument.self.init(url: fileURL as URL)!
        let thing:PDFSelection = PDFSelection.self.init(document: pdfDocument)
        PDFV.setCurrentSelection(thing, animate: true)
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}

但这会导致窗口在我运行它时崩溃,并且 xcode 说:线程 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,子代码 0x0)。有谁知道我实际上打算使用什么?

4

2 回答 2

0

确实没有setDocument方法,但是document您可以使用一个属性:

guard let pdfURL = Bundle.main.url(forResource: "test", withExtension: "pdf")
    else { fatalError("PDF not found") }

guard let pdfDocument = PDFDocument(url: pdfURL)
    else { fatalError("PDF document not created") }

pdfView.document = pdfDocument

此外,无需将 URL 转换为 NSURL,然后再转换回 URL。

于 2017-09-23T09:32:21.573 回答
0

在 Swift 4 中,您可以使用:

  1. 导入PDFKit

  2. 将您的 pdf 复制到您的项目中

  3. 粘贴波纹管代码(测试为pdf文件名)

    let pdfView = PDFView()
    
    pdfView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(pdfView)
    
    pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
    pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
    pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
    pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    
    guard let path = Bundle.main.url(forResource: "test", withExtension: "pdf") else { return }
    
    if let document = PDFDocument(url: path) {
        pdfView.document = document
    }
    
于 2018-06-19T10:21:08.360 回答