0

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.

1 Answers1

3

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
    }
}
Chip Jarred
  • 2,600
  • 7
  • 12
  • You are very right about SwiftUI for macOS app needing work to really be a top notch experience on the Mac. I can't even disable the Show tabs menu item!!! – Tertuliano Máximo Afonso Mar 11 '21 at 23:14
  • Funny you should mention menus. I recently had to deal with that myself. I ended up creating a package that lets you manage the menu bar (aka "main menu") in a SwiftUI way. You define the menus a lot like you define your Views. It's a local package and needs spit and polish, but if you're interested I can make time to put it on GitHub. – Chip Jarred Mar 11 '21 at 23:22
  • The app I am doing is for personal use so there is no schedule to release it and it is not urgent. But I think there are more people with the same problem as me so I would say it would help them. It is crazy how unpolished SwiftUI for macOS is. It looks like the future but it just not there yet. – Tertuliano Máximo Afonso Mar 12 '21 at 00:00
  • @TertulianoMáximoAfonso, I got around to putting my [MacMenuBar](https://github.com/chipjarred/MacMenuBar) package on GitHub, if you want to check it out. It's far from complete, but you might find it useful – Chip Jarred Mar 16 '21 at 09:04