我正在为应用程序编写一个插件 - 自定义键盘快捷键。我可以遍历其观点。 我需要打开弹出菜单,选择其中的项目,然后打开其子菜单并在子菜单中选择一些项目。
现在我只能通过将performClick:
发送到相关的NSPopUpButton
元素来打开顶部弹出菜单。
如何以编程方式选择菜单中的项目并打开其子菜单?
我试过了:
selectItem:
(以及相关NSPopUpButton
)上致电NSMenu
。没有运气,我在doc看到了一个概念:“请注意,当菜单跟踪用户输入时,菜单的程序化更改(如添加,删除或更改菜单上的项目)不会反映出来”答案 0 :(得分:8)
使用NSMenu
方法- (void)performActionForItemAtIndex:(NSInteger)index
NSUInteger idx = [[[menuItem menu] itemArray] indexOfObject:menuItem];
[[menuItem menu] performActionForItemAtIndex:idx];
答案 1 :(得分:2)
对于打开子菜单:performActionForItemAtIndex:
用于选择和打开菜单:
selectItemAtIndex:
+ performClick:
请勿在没有子菜单的项目上调用performActionForItemAtIndex:
,因为您可能会触发可能由其他人设置的操作。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSMenu *menu = self.popup.menu;
NSMenuItem *item = [menu itemAtIndex:2];
[item setAction:@selector(terminate:)];
[item setTarget:NSApp];
}
- (IBAction)action:(id)sender {
//[self.popup.menu performActionForItemAtIndex:2]; -> if not submenu this will quit your app
[self.popup selectItemAtIndex:2]; //-> first select menu item
[self.popup performClick:nil]; //-> open menu - will not quit app
}
答案 2 :(得分:1)
除了@LCC的回答,您还可以在indexOfItem
上致电NSMenu
NSInteger index = [item.menu indexOfItem:item];
[item.menu performActionForItemAtIndex:index];