菜单项目不会出现在nibless StatusMenu应用程序中?

时间:2015-12-07 00:12:58

标签: xcode macos cocoa

我一直在处理一个必须显示状态菜单和一些动态项目的应用程序端口。它的行为类似于苹果WIFI菜单,其中有一个图标,一些固定项目和一些动态项目(可用的WIFI网络)。

出于各种原因,我决定去nibless。我设法显示了菜单图标,但是当我点击图标时,我似乎无法在菜单中显示这些项目。

这是我到目前为止所做的:

AppDelegate.h

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>

// Strange, if these are not properties and not declared strong, 
// the menu flashes momentarily and disappears.  Could the dynamic menu items be related to object lifetime?
@property (strong, nonatomic) IBOutlet NSMenu *statusMenu;
@property (strong, nonatomic) NSStatusItem *statusItem;

@end

AppDelegate.m

import "AppDelegate.h"

@implementation AppDelegate

- (IBAction)loginClicked:(id)sender
{
  NSLog(@"LoginClicked");
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    NSLog(@"AppDidFinishLaunching!");
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
    [self.statusItem setMenu:self.statusMenu];

    NSImage *statusImage = [[NSImage alloc] initWithContentsOfFile:@"/tmp/applogo.png"];
     //menuImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"applogo" ofType:@"png"]];
    [self.statusItem setImage:statusImage];
    [self.statusItem setAlternateImage:statusImage];
    //[self.statusItem setTitle:@"MyApp"];
    [self.statusItem setHighlightMode:YES];

    // Add login
    NSMenuItem *login = [[NSMenuItem alloc] initWithTitle:@"Login" action:loginClicked keyEquivalent:@""];
    [self.statusMenu addItem:login];

    NSMenuItem *quit = [[NSMenuItem alloc] initWithTitle:@"Quit" action:nil keyEquivalent:@""];
    [self.statusMenu addItem:quit];
}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

的main.m

#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"

int main(int argc, const char* argv[])
{
    @autoreleasepool { // Do I need this or is it on by default?
      // make sure the application singleton has been instantiated
      NSApplication * application = [NSApplication sharedApplication];

      // instantiate our application delegate
      AppDelegate * applicationDelegate = [[AppDelegate alloc] init];

      // assign our delegate to the NSApplication
      [application setDelegate:applicationDelegate];

      // call the run method of our application
      [application run];
    }

    // execution never gets here...
    return 0;
}

1 个答案:

答案 0 :(得分:0)

经过多次捣乱后,我尝试了一些现在看似显而易见的事情。

我不知道为什么,但在使用nib的StatusBar应用程序示例中,IBMenu不会被分配和输入。它似乎是以某种方式自动完成的。

添加以下内容似乎解决了这个问题。

self.statusMenu = [[NSMenu alloc] init];

另外,请注意我对终生的评论。如果我不使用属性,我必须在创建statusItem时设置retain。然后它不会被摧毁。我还在了解客观C如何管理对象的生命周期,并且在这里仍然对ARC有点困惑。但它现在似乎最少显示我的菜单项。