Skip to content

Instantly share code, notes, and snippets.

@xpaulnim
Last active January 5, 2024 20:55
Show Gist options
  • Save xpaulnim/7783c8b661740b25d3950090076fc755 to your computer and use it in GitHub Desktop.
Save xpaulnim/7783c8b661740b25d3950090076fc755 to your computer and use it in GitHub Desktop.
Capture mouse scroll events - SwiftUI
// Built this simple example by reading these two files
// - https://github.com/iina/iina/blob/dcb8bbda72a5a725bb68d9eae53f806dc6c72273/iina/PlayerWindowController.swift
// - https://github.com/insidegui/VirtualBuddy/blob/main/VirtualUI/Source/Session/Components/SwiftUIVMView.swift
// - https://stackoverflow.com/questions/64530822
import SwiftUI
struct MouseWheelScrollEventView: NSViewRepresentable {
typealias NSViewType = MouseView
var onMouseScrollEvent: (CGFloat, CGFloat) -> Void
func makeNSView(context: Context) -> MouseView {
let mouseView = MouseView()
mouseView.onMouseScrollEvent = self.onMouseScrollEvent
return mouseView
}
func updateNSView(_ nsView: MouseView, context: Context) {
print("update")
}
class MouseView: NSView {
var onMouseScrollEvent: (CGFloat, CGFloat) -> Void = {(_, _) in }
override func scrollWheel(with event: NSEvent) {
onMouseScrollEvent(event.scrollingDeltaX, event.scrollingDeltaY)
}
}
}
struct LearningCombine: View {
var body: some View {
VStack {
Text("hello world")
MouseWheelScrollEventView { (scrollingDeltaX, scrollingDeltaY) in
print("scrollingDeltaX: \(scrollingDeltaX)")
print("scrollingDeltaY: \(scrollingDeltaY)")
}
// .fixedSize() // uncomment this if you want the View to take up less space
.border(.green, width: 5)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment