I have a NSWindow
. Using NSWindowDelegate
, I can handle windowWillMove()
and windowDidMove()
events. windowWillMove()
is called once, just as the dragging of window starts, which is ideal to recognize the beginning of drag.
However windowDidMove()
is launched whenever window moves, even if the user still drags it. How to recognize that the user ended the drag, and the window now has its final position?
The moment a drag ends is when the user releases the mouse button. In windowDidMove()
, add an event monitor to wait for this.
For example:
// In your NSWindowDelegate:
private var dragEndedMonitor: Any?
func windowDidMove(_ notification: Notification) {
if dragEndedMonitor == nil {
dragEndedMonitor = NSEvent.addLocalMonitorForEvents(matching: [NSEvent.EventTypeMask.leftMouseUp]) { [weak self] event in
if let self, let monitor = self.dragEndedMonitor {
NSEvent.removeMonitor(monitor)
self.dragEndedMonitor = nil
}
print("window drag ended")
// Your work
return event
}
}
}