Skip to content

Instantly share code, notes, and snippets.

@danneu
Created April 7, 2019 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danneu/45f35d1fe3c0a96cd9d424682b798360 to your computer and use it in GitHub Desktop.
Save danneu/45f35d1fe3c0a96cd9d424682b798360 to your computer and use it in GitHub Desktop.
// A view that you can drag to move the underlying window around,
// but other mouse events are still handled by the view.
class DraggableView: NSView {
var dragStart: Date? = nil
// This alone would be sufficient except that the final mouseUp
// after a drag gets handled by the view instead of ignored,
// so the user will accidentally click a button if they happened
// to start (thus end) their drag on one.
override var mouseDownCanMoveWindow: Bool { return true }
// Timestamp the start of any drag.
override func mouseDragged(with event: NSEvent) {
if dragStart == nil {
dragStart = Date()
}
}
// Figure out if the mouseUp terminated a drag or not.
// Also consider tiny drags (<100ms) to be clicks.
override func mouseUp(with event: NSEvent) {
if let dragStart = dragStart {
let milliseconds = (Date().timeIntervalSince1970 - dragStart.timeIntervalSince1970) * 1000
//print("delta", delta)
if milliseconds > 100 {
self.dragStart = nil
return
}
}
super.mouseUp(with: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment