Question

I have a NSStatusItem that has a drop down menu when clicked:

[statusItem setMenu:statusMenu];

Since I'm using a menu, this code will not detect when the status item gets clicked:

[statusItem setAction:@selector(isClicked:)];

How can I use a menu but at the same time know then the status item is clicked?

Was it helpful?

Solution

To accomplish this, you will set up a delegate for the menu.

First, in the interface file (.h) set up the class as a delegate for NSMenu. For example:

@interface MyClass : NSObject <NSMenuDelegate>
. . .
@end

Then in the implementation file (.m) use code like this when initializing your status item:

//your status item initialization code. Then:
[statusItem setMenu:statusMenu];
[statusMenu setDelegate:self];

If you wish, give your menu a title (can be done in Xcode Interface Builder under "Attribute Inspector" if you created your menu in the Interface Builder). Do this to remove discrepancies with other menus.

Then add this method to your class's implementation (.m) file:

-(void)menuWillOpen:(NSMenu *)menu{
    if([[menu title] isEqualToString:@"Menu's title"]){
        //RUN CODE WHEN STATUS ITEM IS CLICKED
    }
}

That's it! You can even use the following code to detect when the menu is closed:

-(void)menuDidClose:(NSMenu *)menu{
    if([[menu title] isEqualToString:@"Menu's title"]){
        //RUN CODE WHEN MENU IS CLOSED
    }
}

You can now know when the status item is clicked, even though you are using a menu.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top