Home > OS >  How to create a menu programmatically without any interface builder files in MacOS?
How to create a menu programmatically without any interface builder files in MacOS?

Time:10-09

I found the question Creating NSMenu with NSMenuItems in it, programmatically? but failed to get the solution to work in my application. I tried combining the code from the question and accepted answer to get the following:

NSMenu *fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
NSMenuItem *newMenu = [[NSMenuItem alloc] initWithTitle:@"New" action:NULL keyEquivalent:@""];
NSMenuItem *openMenu = [[NSMenuItem alloc] initWithTitle:@"Open" action:NULL keyEquivalent:@""];
NSMenuItem *saveMenu = [[NSMenuItem alloc] initWithTitle:@"Save" action:NULL keyEquivalent:@""];
[fileMenu addItem: newMenu];
[fileMenu addItem: openMenu];
[fileMenu addItem: saveMenu];
NSMenuItem *fileMenuItem = [[NSMenuItem alloc] init];
[fileMenuItem setSubmenu: fileMenu];
[[NSApp mainMenu] addItem: fileMenuItem];
[fileMenuItem release];

No File menu is created. Placement of the above code before or after the other code in the main function is inconsequential. I also tried placing in applicationDidFinishLauching to no avail. Why does the above code fail to function, and how can I give my application a menu without using any XIB or Storyboard files?

CodePudding user response:

You just need to add a menubar in order to get your code to run. Could also use addItemWithTitle: and save a few lines of code. If you don't hook up each menuItem to a method they will be grayed out. -buildMenu is usually called from -applicationWillFinishLaunching: in AppDelegate.

- (void) menuAction: (id)sender {
 NSLog(@"%@", sender);
}

- (void) buildMenu {
// **** Menu Bar **** //
 NSMenu *menubar = [NSMenu new];
 [NSApp setMainMenu:menubar];
// **** App Menu **** //
 NSMenuItem *appMenuItem = [NSMenuItem new];
 NSMenu *appMenu = [NSMenu new];
 [appMenu addItemWithTitle: @"Quit" action:@selector(terminate:) keyEquivalent:@"q"];
 [appMenuItem setSubmenu:appMenu];
 [menubar addItem:appMenuItem];
// **** File Menu **** //
 NSMenuItem *fileMenuItem = [NSMenuItem new];
 NSMenu *fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
 [fileMenu addItemWithTitle:@"New" action:@selector(menuAction:) keyEquivalent:@""];
 [fileMenu addItemWithTitle:@"Open" action:@selector(menuAction:) keyEquivalent:@""];
 [fileMenu addItemWithTitle:@"Save" action:@selector(menuAction:) keyEquivalent:@""];
 [fileMenuItem setSubmenu: fileMenu];
 [menubar addItem: fileMenuItem];
}

  • Related