Вопрос

I am programmatically creating an NSMenu with a NSMenuItem. When the window of the application is active, the NSMenuItem is enabled:

Enabled NSMenuItem

However, as soon as the window loses focus the menu item becomes disabled:

Disabled NSMenuItem

Here's how I am creating the NSMenu:

- (void)_quit
{
  [[NSApplication sharedApplication] terminate:nil];
}

- (NSMenu *)_setupMenu
{
  NSMenu *statusMenu = [[NSMenu alloc] initWithTitle:@"Demo"];
  NSMenuItem *quit = [[NSMenuItem alloc] initWithTitle:@"Quit" action:@selector(_quit) keyEquivalent:@""];

  [statusMenu addItem:quit];

  return statusMenu;
}

What is causing this issue? And how do I go about making it enabled regardless of whether the application is in focus or not?

Это было полезно?

Решение

Because menu items are enabled based on the responder chain.

In your case, you can use the terminate: selector instead of your own.
As this is declared in the NSApplication class, which is also part of the responder chain, the item will then be always active.

NSMenuItem *quit = [[NSMenuItem alloc] initWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@""];

More on this here: Cocoa Event Handling Guide

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top