我正在用PDFView类显示一些PDF文件。有一个问题是,当我加载或者更好地说替换另一个文件时,当加载新文件时,最后加载的文件仍然是可见的。

以下是代码:
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)
}发布于 2021-01-10 07:15:37
这里您将pdfView添加为PDFPreview的子视图,但是在第一次尝试删除它时,您将检查它是否存在于self.view的子视图中,而实际上在PDFPreview的子视图中。因此,将其更改为以下代码
func previewPDF(url:URL) {
if PDFPreview.subviews.contains(pdfView) {
self.pdfView.removeFromSuperview() // Remove it
} else {
}而且,当您第二次使用removeFromSuperview()尝试删除它时,您已经实例化了另一个PDFView(),并且丢失了对旧PDFView的引用,因此删除旧PDFView也会失败。
替代解决方案:如果您只是在更改pdf文档,更好的解决方案就是更改PDFView的document属性。例:
if let document = PDFDocument(url: path) {
pdfView.document = document
}https://stackoverflow.com/questions/65552154
复制相似问题