Option (⌥) + Context Menu in Cocoa?

2019-08-09 23:35发布

In a Cocoa application, is there a way to easily allow users to display additional or completely different options in a context menu when they hold down the Option (⌥) key?

Here's it being used in the Volume context menu in the global menu bar:
Here is an image of the Volume context menu in the global Menu bar
Here is an image of the Volume context menu if I hold Option (⌥) before toggling it

It's also used in Finder, but I can't take a screenshot because the shortcut to take a screenshot cancels out the Option (⌥) context menu.

1条回答
贪生不怕死
2楼-- · 2019-08-09 23:45

Take a look at NSView's menuForEvent: method and NSMenuItem's alternate property. The discussion of setAlternate: is missing, here it is:

Discussion

If the receiver has the same key equivalent as the previous item, but has different key equivalent modifiers, the items are folded into a single visible item and the appropriate item shows while tracking the menu, depending on what modifier key (if any) is pressed. The menu items may also have no key equivalent as long as the key equivalent modifiers are different.

Consider the following example: menuItem1 and menuItem2 are menu items in the same menu, with menuItem1 above menuItem2:

[menuItem1 setTitle:@"One"];
[menuItem1 setKeyEquivalent:@"t"];

[menuItem2 setTitle:@"Two"];
[menuItem2 setKeyEquivalent:@"T"];
[menuItem2 setAlternate:YES];

When the menu is displayed, it shows only menuItem1 (with title “One”) instead of two menu items. If the user presses the Shift key while the menu is displayed, menuItem2 (with title “Two”) replaces “One”.

If there are two or more items with no key equivalent but different modifiers, then the only way to get access to the alternate items is with the mouse. In the following example,“Two” is shown only if the user presses the Alternate key.

 [menuItem1 setKeyEquivalent:@""];
 [menuItem1 setTitle:@"One"];

 [menuItem2 setKeyEquivalent:@""];
 [menuItem2 setKeyEquivalentModifierMask:NSAlternateKeyMask];
 [menuItem2 setTitle:@"Two"];

If you mark items as alternates but their key equivalents don’t match, they might be displayed as separate items. Marking the first item as an alternate has no effect.

查看更多
登录 后发表回答