简体   繁体   English

使用Storyboard将NSMenu附加到NSStatusItem

[英]Attach NSMenu to NSStatusItem with Storyboard

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. 我试图在我的Mac OS菜单栏应用程序上单击时,将NSMenu项附加到NSStatusItem以具有菜单。

I am new to Mac programming and I searched tutorials on the Web. 我是Mac编程的新手,我在网上搜索了教程。 However, all the material I found involves the usage of the file Xib to add the NSMenu and linking it to the existing code. 但是,我发现的所有材料都涉及使用NSMenu文件添加NSMenu并将其链接到现有代码。 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. 您可以通过编程方式创建菜单,并将其设置为NSStatusItem如下所示。

- (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. 当然,您可以将NSMenu用作插座。 To do that, drag NSMenu to Application Scene in the storyboard, and connect it to AppDelegate's outlet. 为此,将NSMenu拖到NSMenu中的“应用程序场景”,然后将其连接到AppDelegate的插座。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM