Hi how can I detect when a user option-clicks a Button?
Button("Example") {
if optionKeyDown {
// A
} else {
// B
}
}
I am using the SwiftUI App Lifecycle.
Hi how can I detect when a user option-clicks a Button?
Button("Example") {
if optionKeyDown {
// A
} else {
// B
}
}
I am using the SwiftUI App Lifecycle.
I don't know of a pure SwiftUI way of doing it, but SwiftUI for macOS apps still needs work to really get the UI experience Mac users expect.
However, you can use CoreGraphics.CGEventSource
to achieve what you want:
import CoreGraphics
extension CGKeyCode
{
static let kVK_Option : CGKeyCode = 0x3A
static let kVK_RightOption: CGKeyCode = 0x3D
var isPressed: Bool {
CGEventSource.keyState(.combinedSessionState, key: self)
}
static var optionKeyPressed: Bool {
return Self.kVK_Option.isPressed || Self.kVK_RightOption.isPressed
}
}
The specific key code names in the extension aren't particularly Swifty, so rename them if you like. Those particular names go back to the Classic MacOS Toolbox, and were used in the early days of OS X in the Carbon Event Manager. I tend to keep them for historical reasons. I've created a github gist with of all the old key codes.
With that extension in place, using it is straight-forward. Your code snippet becomes
Button("Example") {
if CGKeyCode.optionKeyPressed {
// A
} else {
// B
}
}