Swift 4:更改/清除PDFView内容

时间:2018-11-26 08:41:59

标签: swift pdfview

我想在Swift 4中使用PDFView框架。(https://developer.apple.com/documentation/pdfkit/pdfview

以下功能接收PDF文档的路径。如果路径有效,则显示PDF文件成功。当我两次致电openMe(path: String)时出现问题。在这种情况下,旧内容仍然存在,并添加了新内容。我只想用新内容更改旧内容。

private var pdfData: NSData? = nil

func openMe(path: String) {
   let fileManager = FileManager.default

   if fileManager.fileExists(atPath: path){
       let url = NSURL.fileURL(withPath: path)
       pdfData = NSData(contentsOfFile: path)
       let pdfView = PDFView(frame: self.view.frame)
       pdfViewController?.pdfViewControllerInformsMeasurementDataViewController = self
       pdfView.document = PDFDocument(url: url)
       pdfView.autoScales = true
       pdfView.maxScaleFactor = 0.5
       pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
       pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

       self.pdfViewController?.view.addSubview(pdfView)
       self.show(self.pdfViewController!, sender: nil)
    }
}

编辑

请参阅兴奋微生物的答案: 我只是像答案中所示更改了代码,但是导航控制器和PDFView之间的距离不同。

拳头openMe通话:

enter image description here

第二个openMe通话:

enter image description here

1 个答案:

答案 0 :(得分:1)

在这种情况下,您需要将pdfView设置为全局:

viewDidLoad()之前添加以下内容:

var pdfView = PDFView()

override func viewDidLoad() {
    super.viewDidLoad()

    // ....
}

然后将代码openMe()编辑为:

func openMe(path: String) {
     if self.pdfViewController?.view.subviews.contains(pdfView) {
          self.pdfView.removeFromSuperview() // Remove it
      } else {
          // Do Nothing
      }

     let fileManager = FileManager.default

   if fileManager.fileExists(atPath: path){
       let url = NSURL.fileURL(withPath: path)
       pdfData = NSData(contentsOfFile: path)
       self.pdfView = PDFView(frame: self.view.frame)
       pdfViewController?.pdfViewControllerInformsMeasurementDataViewController = self
       pdfView.document = PDFDocument(url: url)
       pdfView.autoScales = true
       pdfView.maxScaleFactor = 0.5
       pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
       pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

       self.pdfViewController?.view.addSubview(pdfView)
       self.show(self.pdfViewController!, sender: nil)
     }
}