简体   繁体   中英

iOS: How to clear PDFView?

I am showing some PDF files with PDFView class. There is a problem which is when I load or better to say replace another file, the last loaded file still visible when the new file is loaded.

在此处输入图像描述

Here is the code:

var pdfView = PDFView()
//MARK: - PDF KIT
func previewPDF(url:URL) {
    
    if self.view.subviews.contains(pdfView) {
         self.pdfView.removeFromSuperview() // Remove it
     } else {
        
     }
    
    pdfView = PDFView(frame: PDFPreview.bounds)
    pdfView.removeFromSuperview()
    
    pdfView.backgroundColor = .clear
    pdfView.displayMode = .singlePage
    pdfView.autoScales = true
    pdfView.pageShadowsEnabled = false
    pdfView.document = PDFDocument(url: url)
    
    thumbnail = PDFThumbnail(url: url, width: 240)
    
    // I tried to nil PDFPreview, still nothing happened
    PDFPreview.addSubview(pdfView)
}

Here you are adding pdfView as a subview of PDFPreview but on the first attempt of removing it, you are checking whether it is present in the subview of self.view but actually its in the subview of PDFPreview . So change it to the following code

func previewPDF(url:URL) {
    if PDFPreview.subviews.contains(pdfView) {
       self.pdfView.removeFromSuperview() // Remove it
     } else { 
   
   }

And also when u try to remove it the second time using removeFromSuperview() you have already instantiated another PDFView() and lost the reference to the old one and hence the removal of old PDFView fails at that point too.

Alternate Solution : If you are just changing the pdf document a better solution is just to change the document property of the PDFView. eg:

if let document = PDFDocument(url: path) {
    pdfView.document = document
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM