Skip to content

Instantly share code, notes, and snippets.

@INCHMAN1900
Created September 1, 2024 12:50
Show Gist options
  • Save INCHMAN1900/31b28139162bef41a213e1cab85ae792 to your computer and use it in GitHub Desktop.
Save INCHMAN1900/31b28139162bef41a213e1cab85ae792 to your computer and use it in GitHub Desktop.
Invoke beginDraggingSession programmatically in NSView
class NSView {
override func mouseDown(with event: NSEvent) {
guard event.clickCount <= 2 else { return }
let location = view.convert(event.locationInWindow, from: nil)
let eventMask: NSEvent.EventTypeMask = [.leftMouseUp, .leftMouseDragged]
let timeout = NSEvent.foreverDuration
var dragInitiated = false
view.window?.trackEvents(matching: eventMask, timeout: timeout, mode: .eventTracking, handler: { (event, stop) in
guard let event, event.clickCount <= 2 else { return }
if event.type == .leftMouseUp {
stop.pointee = true
if event.clickCount == 2 {
// Double Click
}
if event.clickCount == 1, !dragInitiated {
// Single Click
}
} else {
let movedLocation = view.convert(event.locationInWindow, from: nil)
if abs(movedLocation.x - location.x) > dragThreshold || abs(movedLocation.y - location.y) > dragThreshold {
stop.pointee = true
dragInitiated = true
var draggingItems = [NSDraggingItem]()
// ...
beginDraggingSession(with: draggingItems, event: event, source: self)
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment