我正在为应用程序编写一个插件 - 自定义键盘快捷键。我可以遍历它的视图。我需要打开弹出菜单,选择其中的项目,然后打开其子菜单并在子菜单中选择一些项目。
现在我只能通过发送performClick:
到相关NSPopUpButton
元素来打开顶部弹出菜单。
如何以编程方式选择菜单中的项目并打开其子菜单?
我试过了:
我正在为应用程序编写一个插件 - 自定义键盘快捷键。我可以遍历它的视图。我需要打开弹出菜单,选择其中的项目,然后打开其子菜单并在子菜单中选择一些项目。
现在我只能通过发送performClick:
到相关NSPopUpButton
元素来打开顶部弹出菜单。
如何以编程方式选择菜单中的项目并打开其子菜单?
我试过了:
使用NSMenu
方法- (void)performActionForItemAtIndex:(NSInteger)index
NSUInteger idx = [[[menuItem menu] itemArray] indexOfObject:menuItem];
[[menuItem menu] performActionForItemAtIndex:idx];
打开子菜单: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
}
除了@LCC 的回答,还可以indexOfItem
拨打NSMenu
NSInteger index = [item.menu indexOfItem:item];
[item.menu performActionForItemAtIndex:index];