objective-cnsmenuitemnsmenunsstatusitem

Remove highlight from NSMenuItem after click?


I have added a custom view to my subclass of NSMenuItem (which sits in a NSStatusMenu), which means that by default it will not get "highlighted" with a blue/gray background.

I implemented this by using the following code:

- (void)drawRect:(NSRect)rect {
  BOOL isHighlighted = [menuItem isHighlighted];
  if (isHighlighted) {
    [[NSColor selectedMenuItemColor] set];
    [NSBezierPath fillRect:rect];
    [menuItem addHover];
  } else {
    [super drawRect:rect];
    [menuItem removeHover];
  }
}

- (void)mouseUp:(NSEvent*)event {
  NSMenuItem *item = [self enclosingMenuItem];
  NSMenu *menu = [item menu];
  [menu cancelTracking];
  [menu performActionForItemAtIndex:[menu indexOfItem:item]];
}

The menu items get highlighted fine, and I can also click on each item; however when I do click on them, they seem to keep the isHighlighted state once I reopen the menu.

Is there a way of changing it so when I click, the highlighted state gets removed when I next open the menu?


Solution

  • I fixed this by removing the mouseUp method in my custom view, and then adding another "hidden" NSView inside it which has the following method:

    - (BOOL)acceptsFirstResponder {
      NSMenu *menu = [item menu];
      [menu cancelTracking];
      [menu performActionForItemAtIndex:[menu indexOfItem:item]];
      return YES;
    }