Skip to content

Instantly share code, notes, and snippets.

@ldenoue
Created July 6, 2024 09:10
Show Gist options
  • Save ldenoue/dfbc834ed471be67d33e06f2184eba03 to your computer and use it in GitHub Desktop.
Save ldenoue/dfbc834ed471be67d33e06f2184eba03 to your computer and use it in GitHub Desktop.
How to detect which mouse button is pressed over a SwiftUI button
struct ContentView: View {
@State private var localMonitor: Any?
@State var hovering = false
@State var mouseButton = -1
var body: some View {
Text("Mouse button")
Button(mouseButton > 1 ? "Button\(mouseButton)" : "Configure") {
}
.foregroundColor(.blue)
.frame(width: 96)
.onHover(perform: { hovering in
self.hovering = hovering
})
.onAppear {
NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown,.rightMouseDown,.otherMouseDown]) { event in
if self.hovering {
if (event.type == .leftMouseDown || event.type == .rightMouseDown) {
mouseButton = -1
} else {
mouseButton = event.buttonNumber
}
}
return event
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment