Change the structure of NSMenu at every opening?

I need to be able to dynamically change the NSMenu hierarchy every time it is displayed (add / remove items, etc.). For instance:

  • the user starts a tracking session in the main menu and selects a submenu
  • detecting a submenu is about to open and run code to change it
  • track user tracks in the same submenu again: goto 2

So, for this I have an object implementing the NSMenuDelegate protocol. The menuNeedsUpdate method works the first time (2), but does not work the second time a submenu opens. (Called only once per tracking session)

The menuWillOpen method is called every time, but has the following docs warning, which appears to be disqualified using this approach:

Do not change the structure of menus or menu items during this method.

Is there any way to do this?

+6
objective-c cocoa nsmenu nsmenuitem
source share
2 answers

You can subclass NSMenu and override the Action: submenu .

Or you can simply subscribe to NSMenuWillSendActionNotification .

And while it doesn't seem like it will work for you, just for reference, NSMenuValidation is a good place to update menu items individually.

0
source share

menuWillOpen will only be called once, the first time you track a submenu. At this point, you are filling out the menu.

After that, menuWillOpen will not be called again. However, any changes to the menu will occur live. Therefore, when the main parent menu is open, whenever the original data changes (or periodically if you cannot detect the changes), update the menu using the regular NSMenu API.

Make sure that any method you use to update the menu will be executed while the system monitors your menu.

0
source share

All Articles