Created
July 6, 2024 09:10
-
-
Save ldenoue/dfbc834ed471be67d33e06f2184eba03 to your computer and use it in GitHub Desktop.
How to detect which mouse button is pressed over a SwiftUI button
This file contains 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
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