I am trying to attach an NSMenu
item to a NSStatusItem
to have a menu when clicking on my Menu Bar App for Mac OS.
I am new to Mac programming and I searched tutorials on the Web. However, all the material I found involves the usage of the file Xib to add the NSMenu
and linking it to the existing code. However, I don't have such a file in my project, it only includes the storyboard file.
I hope you can help.
Cheers
You can create a menu programmatically and set it to NSStatusItem
like this.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
_statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:30];
_statusItem.image = [NSImage imageNamed:@"..."];
// create menu
NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
NSMenuItem *item1 = [[NSMenuItem alloc] initWithTitle:@"menu1" action:@selector(menu1Action:) keyEquivalent:@""];
NSMenuItem *item2 = [[NSMenuItem alloc] initWithTitle:@"menu2" action:@selector(menu2Action:) keyEquivalent:@""];
[menu addItem:item1];
[menu addItem:item2];
[_statusItem setMenu:menu]; // attach
}
Of course, you can use NSMenu
as outlet. To do that, drag NSMenu
to Application Scene in the storyboard, and connect it to AppDelegate's outlet.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.