2

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

4

1 回答 1

4

我猜是,您正在搜索子菜单项。通过搜索子菜单在 Interface Builder 中找到它。

在此处输入图像描述

插入所需的菜单后,您会发现一个名为 Item 的新条目。只需编辑这些和/或根据需要填写其他菜单项。这会根据您的要求创建一个菜单结构!

在此处输入图像描述

  • 编辑 *

我为您的问题提供了解决方案。根据 Apple Docs 上下文菜单位于它们所属的视图中。从 viewController `viewDidLoad 调用方法。选择器方法根据需要创建。

* 编辑 * 将创建的菜单分配给主菜单。我在viewDidLoad方法中做到了这一点。如果您不喜欢将它放在顶部的主菜单上,只需跳过 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 {

}

我测试了它并且它有效!这里是截图。在此处输入图像描述

希望能帮助到你。当它出现时,使用绿色回答菜单:-)

于 2017-03-01T20:38:14.320 回答