2

I'm attempting to use the isAlternative property with an NSMenuItem with a custom view. It is not behaving as a standard NSMenuItem without a custom view. How do I get the standard modifier-key toggling behavior when using NSMenuItems with custom views?

Standard Menu Item behavior

Add a menu item. Add an additional menu item with .isAlternate == true and .keyEquivalentModifierMask = [ .option ] (or another appropriate modifier key).

When the menu is displayed, the first menu item is displayed. While the modifier key is held, the original menu item is replaced with the alternate menu item.

Custom Menu Item behavior

Add a menu item with a custom view. Add an additional menu item with a custom view with .isAlternate == true and .keyEquivalentModifierMask = [ .option ] (or another appropriate modifier key).

When the menu is display, instead of the standard toggling behavior, both the original and the alternate menu items are shown at all times.

Reference

GitHub example project

Ian Gordon
  • 41
  • 3
  • AFAIK you can't - it doesn't work with `isAlternative` and you have to implement it yourself. – zrzka Jul 22 '20 at 14:48
  • Unfortunately, as far as I can tell, keyboard events (including modifier flags) are not propagated to the NSMenu. If I setup an external event listener I would need to ask the user for full accessibility permissions which seems excessive. Is there an easy or obvious way to add a keyboard handler that I'm overlooking? – Ian Gordon Jul 31 '20 at 22:50

1 Answers1

0

How to set up an alternate NSMenuItem

  1. Set isAlternate to true
  2. Define a keyEquivalentModifierMask
let alternativeMenuItem = NSMenuItem("alternative", action: nil, keyEquivalent: "")
alternativeMenuItem.isAlternate = true
alternativeMenuItem.keyEquivalentModifierMask = [.option]
ixany
  • 5,433
  • 9
  • 41
  • 65