简体   繁体   English

iOS:如何清除 PDFView?

[英]iOS: How to clear PDFView?

I am showing some PDF files with PDFView class.我正在使用PDFView class 显示一些 PDF 文件。 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 .在这里,您将 pdfView 添加为 PDFPreview 的子视图,但在第一次尝试删除它时,您正在检查它是否存在于 self.view 的子视图中,但实际上它位于 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.而且,当您第二次尝试使用 removeFromSuperview() 删除它时,您已经实例化了另一个 PDFView() 并丢失了对旧 PDFView 的引用,因此删除旧 PDFView 也失败了。

Alternate Solution : If you are just changing the pdf document a better solution is just to change the document property of the PDFView.替代解决方案:如果您只是更改 pdf 文档,更好的解决方案是更改 PDFView 的文档属性。 eg:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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