4

I have a list of user-configurable things that show in a main menu submenu. The first 9 items get the shortcuts ⌘1--⌘9 assigned:

let item = theMenu.addItem(
    withTitle: title, 
    action: #selector(itemSelected(_:)), 
    keyEquivalent: "1")
item.target = self
item.keyEquivalentModifierMask = [.command]

The shortcut ⌘1 doesn't work until you open the menu once. After that, it works as expected. This setup code is called on launch, by the way.

Could this be an issue of menu item validation? Or is this approach just inferior to a menu with a delegate?

ctietze
  • 2,805
  • 25
  • 46
  • Did you ever find an answer here? – Craigt Jul 28 '21 at 06:29
  • @Craigt I ended up letting users pick shortcuts, and I don't recall this being an issue anymore. I also do not recall figuring out how to fix this. So it's still a mystery in my books. – ctietze Jul 29 '21 at 15:02

1 Answers1

0

You should create the NSMenuItem fisrt an then add it to NSMenu:

let item = NSMenuItem(
    title: title, 
    action: #selector(itemSelected(_:)), 
    keyEquivalent: "1"
)
item.keyEquivalentModifierMask = [.command]
theMenu.addItem(item)

Alex
  • 124
  • 1
  • 4
  • Can you explain what this does differently? – ctietze Mar 20 '23 at 09:56
  • I can't explain but I tried and this works – Alex Mar 20 '23 at 17:34
  • A notable difference is the lack of a target, as in `item.target = self`, so it's the first responder. That might do the trick for early menu item enablement? To be fair, the bug went away for my users in the past 5 years :) – ctietze Apr 26 '23 at 06:45
  • @ctietze Sorry I made a wrong answer. For now I think the shortcut assigned to a `NSMenuItem ` only works when the menu is open. – Alex Apr 28 '23 at 07:54