问题描述
我正在使用PDFKit,并且类似于Apple Preview App,当添加PDF注释时,我希望用户能够在页面上四处移动它们。我创建了一个example project on 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,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)
工作顺利。