Swift 4: Change / Clear PDFView content

和自甴很熟 提交于 2021-01-29 19:09:59

问题


I want to use PDFView framework in Swift 4. (https://developer.apple.com/documentation/pdfkit/pdfview)

The following function receives a path to a PDF document. If the path is valid, the PDF file is successful shown. A problem occurs, when I call openMe(path: String) twice. In this case, the old content is still there and the new content is added. I just want to change the old content with the new content.

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)
    }
}

EDIT

Refer to excitedmicrobe's answer: I just changed the code like shown in the answer but the distance between the navigation controller and the PDFView differs.

Fist openMe call:

Second openMe call:


回答1:


In that case, you would need to make your pdfView global:

Before viewDidLoad() add the following:

var pdfView = PDFView()

override func viewDidLoad() {
    super.viewDidLoad()

    // ....
}

And edit your code openMe() to:

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)
     }
}


来源:https://stackoverflow.com/questions/53477361/swift-4-change-clear-pdfview-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!