双PDFView同步更新异常:添加高亮批注后仅另一视图显示
两个PDFView同步批注异常的原因与修复方案
你遇到的问题很典型——两个绑定同一PDF文档的PDFView,只有最后赋值的那个能同步显示批注,先赋值的视图完全没反应。哪怕手动调用刷新方法也没用,调换赋值顺序还会反转问题。
异常原因
核心问题出在PDFDocument的delegate机制上:
当你把同一个PDFDocument实例赋值给多个PDFView时,每个PDFView在设置document属性时,都会自动将自身设置为该文档的delegate,覆盖之前的delegate。也就是说:
- 先给
firstPDF赋值时,firstPDF成为文档的delegate - 接着给
secondPDF赋值时,secondPDF会替换掉之前的delegate,成为文档唯一的delegate
当你添加批注时,PDFDocument只会向当前的delegate(也就是最后绑定的那个PDFView)发送变更通知,触发它刷新显示。而第一个PDFView因为不再是delegate,根本收不到任何变更通知——哪怕你手动调用needsDisplay或者displayIfNeeded也没用,这些方法只是刷新视图当前缓存的内容,不会主动去文档里重新读取最新的批注数据。
修复方案
有两种简单的修复方式,根据你的需求选择:
方案1:手动通知两个视图刷新批注
在添加批注后,手动调用两个PDFView的annotationsChanged(on:)方法,强制它们重新读取页面上的批注并刷新。修改你的highlightPDF方法:
@IBAction func highlightPDF(_ sender: Any) { firstPDF.highlight() // 获取当前选中的页面,同时通知两个视图刷新 if let page = firstPDF.currentPage { firstPDF.annotationsChanged(on: page) secondPDF.annotationsChanged(on: page) } }
这个方法简单直接,适合你的现有代码结构,不需要额外修改其他逻辑。
方案2:自定义PDFDocumentDelegate,全局监听批注变更
如果后续还要支持删除、修改批注等操作,推荐用这种方式,一次性解决所有同步问题:
- 让你的
ViewController遵守PDFDocumentDelegate协议 - 在加载PDF时,手动设置文档的delegate为当前控制器
- 实现批注变更的回调方法,通知两个视图同步刷新
修改后的代码如下:
class ViewController: NSViewController, PDFDocumentDelegate { @IBOutlet weak var firstPDF: PDFView! @IBOutlet weak var secondPDF: PDFView! @IBAction func selectPDF(_ sender: Any) { if let url = askForFile(), let pdf = PDFDocument(url: url) { // 设置自定义delegate,替换PDFView默认的delegate pdf.delegate = self firstPDF.document = pdf secondPDF.document = pdf } } @IBAction func highlightPDF(_ sender: Any) { firstPDF.highlight() // 这里不需要手动刷新了,delegate方法会自动处理 } // MARK: - PDFDocumentDelegate func documentDidAddAnnotation(_ notification: Notification) { guard let annotation = notification.userInfo?[PDFDocumentAnnotationNotificationKey] as? PDFAnnotation, let page = annotation.page else { return } syncAnnotations(on: page) } func documentDidRemoveAnnotation(_ notification: Notification) { guard let annotation = notification.userInfo?[PDFDocumentAnnotationNotificationKey] as? PDFAnnotation, let page = annotation.page else { return } syncAnnotations(on: page) } // 统一处理两个视图的批注刷新 private func syncAnnotations(on page: PDFPage) { firstPDF.annotationsChanged(on: page) secondPDF.annotationsChanged(on: page) } }
这个方案的好处是,无论通过哪种方式(比如右键菜单、代码添加)修改批注,两个视图都会自动同步,不需要在每个操作里手动写刷新逻辑。
内容的提问来源于stack exchange,提问作者Tom J
相关产品推荐
相关产品推荐

