cody
cody

Reputation: 3277

NSMenu programmatically select item

I'm writing a plugin for application - custom keyboard shortcut. I can traverse through its views. I need to open popup menu, select item in it, then open its submenu and select some item in submenu.

For now I'm only able to open top popup menu by sending performClick: to related NSPopUpButton element.

How can I programmatically select item in menu and open its submenu?

I've tried:

Upvotes: 11

Views: 5819

Answers (3)

Marek H
Marek H

Reputation: 5566

For opening submenu: performActionForItemAtIndex:

For selecting and opening menu: selectItemAtIndex: + performClick:

Do not call performActionForItemAtIndex: on item that does not have submenu cause you might trigger action that might have been set by someone else.

- (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
}

Upvotes: 4

onmyway133
onmyway133

Reputation: 48085

In addition to @LCC 's answer, you can also call indexOfItem on NSMenu

NSInteger index = [item.menu indexOfItem:item];
[item.menu performActionForItemAtIndex:index];

Upvotes: 1

LCC
LCC

Reputation: 1225

Use the NSMenu method - (void)performActionForItemAtIndex:(NSInteger)index

NSUInteger idx = [[[menuItem menu] itemArray] indexOfObject:menuItem];
[[menuItem menu] performActionForItemAtIndex:idx];

Upvotes: 9

Related Questions