我正在尝试为mac(不是IOS)制作PDF查看器,但我甚至无法弄清楚如何让PDF实际显示出来。我们必须使用PDFView和Quartz。 我在这个主题上看到的大多数教程都使用了类似的东西:
view.setDocument(pdf)
但swift说PDFView没有成员setDocument。我仔细查看了文档here,并且唯一可以远程查看它的工作就是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(代码= EXC_I386_INVOP,子代码0x0)。有谁知道我实际上打算使用什么?
答案 0 :(得分: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。
答案 1 :(得分:0)
在Swift 4中您可以使用
粘贴以下代码(测试为pdf文件名)
让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
}