Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMenu items greyed/disabled for not apparent reason

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.

enter image description here

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?

like image 822
benstpierre Avatar asked Oct 22 '15 22:10

benstpierre


1 Answers

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];
like image 162
A O Avatar answered Oct 19 '22 11:10

A O