xcode 带有菜单栏图标的简单 Cocoa 应用程序。如何:?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4755875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:07:25  来源:igfitidea点击:

Simple Cocoa application with MenuBar Icon. How To:?

cocoaxcodemacos

提问by Zrb0529

I'm trying to make a Cocoa application that's pretty simple. I have three windows with three messages on them, that's all there is to it. What I'm trying to do is this:

我正在尝试制作一个非常简单的 Cocoa 应用程序。我有三个窗口,上面有三个消息,仅此而已。我想要做的是:

The user runs the app, the app icon appears in the menu bar and that's all that happens, no menu and no dock icon

用户运行应用程序,应用程序图标出现在菜单栏中,仅此而已,没有菜单也没有停靠栏图标

Then, the user can click the MenuBar Icon and have a dropdown list and choose from the three available messages.

然后,用户可以单击 MenuBar 图标并有一个下拉列表并从三个可用消息中进行选择。

I know it's useless, but this is literally my first application and I can't figure out how to get NSStatusItem to work properly...

我知道它没用,但这实际上是我的第一个应用程序,我不知道如何让 NSStatusItem 正常工作......

I've looked around and found some tutorials but I can't seem to follow any of them...any help?

我环顾四周并找到了一些教程,但我似乎无法遵循其中的任何一个......有什么帮助吗?

回答by Eimantas

  1. Regarding the "no dock icon" - add boolean LSUIElemententry to Info.plist file and set it to true. This won't show application in app switcher UI (cmd+tab) as well.
  2. Adding menu bar icon is as much as looking into NSStatusBarand NSStatusItemdocumentation and using example code there:
  1. 关于“无停靠图标” -LSUIElement向 Info.plist 文件添加布尔条目并将其设置为true。这也不会在应用程序切换器 UI(cmd+tab)中显示应用程序。
  2. 添加菜单栏图标是尽可能寻找到NSStatusBarNSStatusItem文档,并使用示例代码有:

.

.

// this one is taken from apple documentation
- (void)activateStatusMenu {
    NSStatusBar *bar = [NSStatusBar systemStatusBar];

    theItem = [bar statusItemWithLength:NSVariableStatusItemLength];
    [theItem retain];

    [theItem setTitle: NSLocalizedString(@"Tablet",@"")];
    [theItem setHighlightMode:YES];
    [theItem setMenu:theMenu];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self activateStatusMenu];
}

UpdateSince ARC does not allow retaincalls in the code, I managed to solve the issue by creating theItemas __stronginstance variable of the class where the item is being created.

更新由于ARC不允许retain在代码中调用,我设法通过创建来解决问题,theItem因为__strong那里正在创建该项目的类的实例变量。