如何在PDFView中移动PDF页面上的PDF注释



我使用PDFKit,类似于Apple Preview应用程序,在添加PDF注释时,我希望用户能够在页面上移动它们。我在Github上创建了一个示例项目。

我已经尝试过将PDFView子类化并覆盖func mouseDown(with event: NSEvent)func mouseDragged(with event: NSEvent)。我可以分享这些代码,但我有一种直觉,我正朝着错误的方向前进。(我想这种感觉是由我无法使代码工作的事实所证实的…(

编辑:我已经将以下代码添加到我的PDFView中。它有效,但并不优雅。它并不像预览应用程序那样流畅。只是想在这里学习,所以也许有人有更好的方法?

private var annotationBeingDragged:PDFAnnotation?
override func mouseDown(with event: NSEvent) {
let areaOfInterest = self.areaOfInterest(forMouse: event)
if areaOfInterest.contains(.annotationArea),
let currentPage = self.currentPage,
let annotation = currentPage.annotation(at: self.convert(self.convert(event.locationInWindow, from: nil), to: currentPage)) {
if annotationBeingDragged == nil {
annotationBeingDragged = annotation
} else {
super.mouseDown(with: event)
}
}
else {
super.mouseDown(with: event)
}
}
override func mouseDragged(with event: NSEvent) {
if let annotation = annotationBeingDragged,
let currentPage = self.currentPage {

currentPage.removeAnnotation(annotation)
let currentPoint = self.convert(self.convert(event.locationInWindow, from: nil), to: currentPage)
annotation.bounds = NSRect(origin: currentPoint, size: annotation.bounds.size)
currentPage.addAnnotation(annotation)
}
else {
super.mouseDragged(with: event)
}
}
override func mouseUp(with event: NSEvent) {
if annotationBeingDragged != nil {
annotationBeingDragged = nil
super.mouseDown(with: event)
}
else {
super.mouseUp(with: event)
}
}

它是mouseUp方法更改中代码的微小更改。

super.mouseDown(with: event)

super.mouseUp(with: event)

其工作顺利。

最新更新