我开始使用 PDFKit,在根目录中有一个 pdf 文件,它使用以下代码:
if let path = Bundle.main.path(forResource: "mypdf1", ofType: "pdf") {
let url = URL(fileURLWithPath: path)
if let pdfDocument = PDFDocument(url: url) {
pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displayDirection = .vertical
pdfView.document = pdfDocument
print(path)
}
}
但是,如果我更改目录中的 pdf 文件,例如“mydirectory”,则不起作用,我的代码如下:
if let path = Bundle.main.path(forResource: "mypdf1", ofType: "pdf", inDirectory: "mydirectory") {
let url = URL(fileURLWithPath: path)
if let pdfDocument = PDFDocument(url: url) {
pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displayDirection = .vertical
pdfView.document = pdfDocument
}
}
任何解决路径问题的建议。
更新
根据建议,尝试以下代码,但我也无法可视化 PDF。
if let documentURL = Bundle.main.url(forResource: "mypdf1", withExtension: "pdf", subdirectory: "mydirectory") {
if let document = PDFDocument(url: documentURL) {
pdfView.autoScales = true
pdfView.backgroundColor = UIColor.lightGray
pdfView.document = document
}
}
您从子目录读取 pdf 的代码是正确的,当我阅读它们时,路径中的值为零,这肯定是因为您的容器文件夹未正确创建。你可以看到黄色和蓝色的文件夹,你的容器文件夹应该是蓝色的。
要制作蓝色文件夹,您应该执行以下步骤:
您将获得蓝色的文件夹,您的代码可以读取 pdf。
Xcode 中有两种类型的文件夹:组和文件夹引用。您可以使用组来组织项目中的文件,而不会影响它们在实际文件系统上的结构。这对代码非常有用,因为您将只在 Xcode 中处理您的代码。另一方面,组不太适合资源文件。
在任何相当复杂的项目中,您通常会处理数十个(如果不是数百个)资产文件,并且这些资产需要由您或设计师从 Xcode 外部修改和操作。将所有资源文件放在一个平面文件夹中是一种灾难。这就是文件夹引用的用武之地。它们允许您将文件组织到文件系统上的文件夹中,并在 Xcode 中保持相同的文件夹结构。
蓝色用于表示“文件夹引用”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句