I'm working with PDFKit and similar to the Apple Preview App, when adding PDF annotations, I'd like the user to be able to move them around on the page. I've created an example project on Github.
I've tried subclassing PDFView and overriding func mouseDown(with event: NSEvent)
and func mouseDragged(with event: NSEvent)
. I can share that code, but I have the gut feeling that I'm heading in the wrong direction there. (I suppose that feeling is substantiated by the fact that I cannot get that code to work...)
Edit: I've added the following code to my PDFView. It works, but it doesn't work elegantly. It's not nearly as smooth as the way the preview app works. Just trying to learn here, so maybe someone has a better way of doing it?
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)
}
}
it small change in your code in your
mouseUp
method change.to
its work smoothly.