I have the following code that starts up a "tray icon" and adds a NSMenu to it.
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
@interface TrayIcon : NSObject
@property(strong) NSStatusItem *statusItem;
- (void)makeTrayIcon;
- (void)stopServer:(nullable id)sender;
- (void)startServer:(nullable id)sender;
@end
and...
#import "TrayIcon.h"
@implementation TrayIcon {
}
- (void)makeTrayIcon {
// Flycut/AppController.h
IBOutlet NSMenu *jcMenu;
// Flycut/AppController.m
_statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[_statusItem setHighlightMode:YES];
[_statusItem setImage:[NSImage imageNamed:@"16.png"]];
[_statusItem setMenu:jcMenu];
[_statusItem setEnabled:YES];
//Add Menu
{
NSMenu *menu = [[NSMenu alloc] init];
[menu addItemWithTitle:@"Start Server" action:@selector(startServer:) keyEquivalent:@""];
[menu addItemWithTitle:@"Stop Server" action:@selector(stopServer:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@""];
_statusItem.menu = menu;
}
}
- (void)stopServer:(nullable id)sender {
NSLog(@"Stop STUFF");
}
- (void)startServer:(nullable id)sender {
NSLog(@"Start STUFF");
}
@end
For some reason my menu looks like this.
Why would Quit be enabled but "Start Server" and "End Server" not be? By using @selector(terminate:) on Start/Stop server they become enabled. Perhaps I have bad syntax in my methods startServer and stopServer?
We have similar code, and I removed the -setTarget
call and saw the disabled state.
As Willeke stated, it is because your object isn't in the responder chain.
So just make sure you explicitly set the target
property:
NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"Start" action:@selector(startServer:) keyEquivalent:@""];
[item setTarget:self];
[menu addItem:item];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With