Search code examples
objective-cnsstatusbar

How to access NSStatusBar from another view?


I have status bar icon and I'm trying to add right click menu.

   statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];       
   MyView *view = [MyView new];
   view.image = statusImage;
   [statusItem setView:view];
   [statusItem setToolTip:@"Program Name"];
   view.target = self;
   view.action = @selector(openLeftWindow:);
   view.rightAction = @selector(openRightWindow:);

in other view I am able to get if NSStatusBar was pressed with left or right button. And on right click event i'm trying to add NSMenu. I figure I could add menu like this:

[statusItem setMenu:theMenu];

But I can't because I have no statusItem. I'm very new at this so maybe it isn't even the right way to do this.

EDIT: Somehow I managed to make the menu show. I'm not sure it's the right way to do this, but all I did was assign statusItem to my custom view like this:

view.statusItem = statusItem;

Added this to the custom view header file:

@property NSStatusItem *statusItem;

and show menu like this:

[self.statusItem popUpStatusItemMenu:theMenu];

Solution

  • I'm not quite sure what your question is, but in the old days you could call -popStatusItemMenu on your `NSStatusItem instance to show a menu (particularly in a view action such as your openRightWindow:): https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSStatusItem_Class/index.html#//apple_ref/occ/instm/NSStatusItem/popUpStatusItemMenu:

    If it's a problem of getting access to your instance of the status item, I suggest you add that property to MyView so that you could reference it.

    However, as of 10.10 you should be using NSStatusBarButton which I can't seem to find documentation online for. You may need to check header files.