我是swift的新手,正在尝试弄清楚如何对我的数组进行编码以包含PDF文档。我设置了一个tableView,因为当单元格被单击时,它将移动到一个新的细节视图控制器。我希望新的详细信息控制器显示与所选单元格相关联的PDF。有没有一种智能的方法来编码呢?
我一直在为如何编写这部分代码而苦苦挣扎。
import Foundation
import UIKit
import PDFKit
class State
{
var title: String
var detailText: String
var description: String
var image: UIImage
var document: PDFDocument
init(titled: String, detailText: String, imageName: String, description: String, document: String)
{
self.title = titled
self.detailText = detailText
self.description = description
self.document = PDFDocument
if let img = UIImage(named: imageName){
image = img
} else {
image = UIImage(named: "default")!
}
}
}我试图让代码将“PDFDocument”识别为一个文档,但我得到了一个错误:无法将'PDFDocument.Type‘类型的值赋给'PDFDocument’类型,这是哪里错了?
发布于 2019-03-26 09:10:13
错误的原因是您试图将类型(PDFDocument)分配给self.document,而不是传递给init - document的参数。此外,参数的类型必须是PDFDocument,而不是String。
import Foundation
import UIKit
import PDFKit
class State
{
var title: String
var detailText: String
var description: String
var image: UIImage
var document: PDFDocument
init(titled: String, detailText: String, imageName: String, description: String, document: PDFDocument)
{
self.title = titled
self.detailText = detailText
self.description = description
self.document = document
if let img = UIImage(named: imageName){
image = img
} else {
image = UIImage(named: "default")!
}
}
}除非你因为其他原因而需要让State成为一个类,否则我建议让它成为一个结构--这就提供了隐式的不变性。您还可以使用nil合并运算符简化该if语句
import Foundation
import UIKit
import PDFKit
struct State
{
var title: String
var detailText: String
var description: String
var image: UIImage
var document: PDFDocument
init(titled: String, detailText: String, imageName: String, description: String, document: PDFDocument)
{
self.title = titled
self.detailText = detailText
self.description = description
self.document = document
self.image = UIImage(named: imageName) ?? UIImage(named: "default")!
}
}好的,
您的实际问题似乎是“如何从我的应用程序包中获取PDFDocument?”
您可以使用类似以下内容:
if let path = Bundle.main.path(forResource: "SomePdfFile", ofType: "pdf") {
do {
let fileUrl = URL(fileURLWithPath: path)
if let pdfDocument = PDFDocument(url:fileURL) {
// Do something with PDFDocument
}
} catch {
print("There was an error - \(error)")
}
}您可以将其转换为一个函数:
func loadPDF(named: String) throws -> PDFDocument? {
guard let path = Bundle.main.path(forResource: "SomePdfFile", ofType: "pdf") else {
return nil
}
let fileUrl = URL(fileURLWithPath: path)
return PDFDocument(url:fileURL)
}https://stackoverflow.com/questions/55348313
复制相似问题