Last active
April 4, 2024 16:31
-
-
Save davidbalbert/84104bc0e2997ed760b7834fae241869 to your computer and use it in GitHub Desktop.
Classic AppKit autoscroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
class MyAutoscrollingView: NSView { | |
override func mouseDown(with event: NSEvent) { | |
// mouseDown-specific logic here | |
var mouseEvent = event | |
var done = false | |
NSEvent.startPeriodicEvents(afterDelay: 0.1, withPeriod: 0.05) | |
while !done { | |
guard let nextEvent = NSApp.nextEvent(matching: [.leftMouseUp, .leftMouseDragged, .periodic], until: .distantFuture, inMode: .eventTracking, dequeue: true) else { | |
print("Unexpected nil event, should not expire") | |
continue | |
} | |
switch nextEvent.type { | |
case .periodic: | |
autoscroll(with: mouseEvent) | |
mouseDraggedOrAutoscroll(with: event) | |
case .leftMouseUp: | |
done = true | |
NSApp.sendEvent(nextEvent) | |
case .leftMouseDragged: | |
mouseEvent = nextEvent | |
NSApp.sendEvent(nextEvent) | |
default: | |
fatalError("unexpected event", nextEvent) | |
} | |
} | |
NSEvent.stopPeriodicEvents() | |
} | |
override func mouseDragged(with event: NSEvent) { | |
// mouseDragged-specific logic here | |
mouseDraggedOrAutoscroll(with: event) | |
} | |
override func mouseUp(with event: NSEvent) { | |
// mouseUp-specific logic here | |
} | |
func mouseDraggedOrAutoscroll(with event: NSEvent) { | |
// things that should happen both on mouseDragged and on autoscroll | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment