Skip to content

Instantly share code, notes, and snippets.

@davidbalbert
Last active April 4, 2024 16:31
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 davidbalbert/84104bc0e2997ed760b7834fae241869 to your computer and use it in GitHub Desktop.
Save davidbalbert/84104bc0e2997ed760b7834fae241869 to your computer and use it in GitHub Desktop.
Classic AppKit autoscroll
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