How to create logical groups inside a context menu. Mac OS

927 views Asked by At

I want to create logical groups by separating out the menu items in my sub menu.

Similar to the open with sub menu in Mac.

How can I achieve this.

NSMenuItem Separator Item creates a blank space, I require the visual to be the same as in the image attached. enter image description here

1

There are 1 answers

10
voltae On

I guess is, you are searching for Submenu Item. Find it in the Interface Builder by searching for submenu.

enter image description here

After inserting in the desired menu you find a new entry called Item. Just edit these and or fill in other menu items as you like. This creates a menu structure as you asked for!

enter image description here

  • Edit *

I provided you a solution for your question. According to the Apple Docs Context menus are located in the views in which they belong. Call the method from the viewController `viewDidLoad. the selector method create as you need.

* Edit * Assign the created menu to the main menu. I did this in the viewDidLoad method. if you don't like to have it on the main menu on the top, just skip the two lines after the mainmenu comment. BTW the index is the position in which the menu get inserted in the mainmenu.

- (void)viewDidLoad {
    [super viewDidLoad];
    [[self view] setMenu:[self contextMenu]];

    NSMenuItem *subMenu = [[NSMenuItem alloc] init];
    subMenu.submenu = [self contextMenu];

    // Add the menu in mainmenu as well
    NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
    [mainMenu insertItem:subMenu atIndex:3];
   }

-(NSMenu *)contextMenu {

    NSMenu *contextMenu = [[NSMenu alloc] initWithTitle:@"Contextmenu"];

    NSMenuItem *subMenuItem = [[NSMenuItem alloc] init];
    [subMenuItem setEnabled:YES];
    [subMenuItem setTarget:self];
    [subMenuItem setEnabled:YES];

    NSMenu *subMenu = [[NSMenu alloc] initWithTitle:@"Submenu"];
    subMenuItem.submenu = subMenu;
    [subMenuItem setTitle:[subMenu title]];

   // Creates the menu entries.
    NSMenuItem *menuItem1 = [[NSMenuItem alloc] initWithTitle:@"otherMenu" action:@selector(subMenuAction:) keyEquivalent:@""];
    NSMenuItem *menuItem2 = [[NSMenuItem alloc] initWithTitle:@"anotherMenu" action:@selector(subMenuAction:) keyEquivalent:@""];

 // Creates the separator.
   NSMenuItem *separator = [NSMenuItem separatorItem];

  [subMenu addItem:menuItem1];
  [subMenu addItem:separator];
  [subMenu addItem:menuItem2];


  [contextMenu addItem:subMenuItem];

  return contextMenu;

 }

- (void)subMenuAction:(id)sender {

}

I tested it and it works! Here the screenshot.enter image description here

Hope it helps. And when it does, use the green answered menu :-)