我正在使用 PDFKit 并且类似于 Apple Preview App,在添加 PDF 注释时,我希望用户能够在页面上移动它们。我在 Github 上创建了一个示例项目。
我尝试子类化 PDFView 并覆盖func mouseDown(with event: NSEvent)
and 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)
}
}