3

I want to customize an an NSPopUpButton so I have implemented an CustomMenuItemView which right now only has the following code (for testing purposes):

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor redColor] set];
    NSRectFill(dirtyRect);
}

Now, for every NSMenuItem i add to the NSMenu in myPopUpButton.menu I set the view to my custom view:

NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@"Some title" action:NULL keyEquivalent:@""];
menuItem.view = [[CustomMenuItemView alloc] initWithFrame:NSMakeRect(0, 0, 100, 25)];

When I run my program and open the popup button the menuitem selection seems disabled (i.e. nothing happens when I click on it).

I am guessing that it is not actually disabled; it just doesn't respond to events anymore. Do I need to add some event handling in my custom view? If so, how?

pajevic
  • 4,607
  • 4
  • 39
  • 73
  • 1
    "A menu item with a view does not draw its title, state, font, or other standard drawing attributes, and assigns drawing responsibility entirely to the view." - https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSMenuItem_Class/Reference/Reference.html – Mazyod Apr 16 '12 at 07:31

1 Answers1

10

I solved the problem by adding the mouseUp method to my CustomMenuItemView:

- (void)mouseUp:(NSEvent*) event
{
    NSMenu *menu = self.enclosingMenuItem.menu;
    [menu cancelTracking];
    [menu performActionForItemAtIndex:[menu indexOfItem:self.enclosingMenuItem]];
}
pajevic
  • 4,607
  • 4
  • 39
  • 73
  • I have the same problem, just few years later. Your solution only handles mouse clicks, but I’m trying to handle keyboard navigation, too. Pressing Enter/Return or Space selects the highlighted menu item and closes the menu, but no action is sent. Overriding `-keyUp:` doesn’t work, Do you have any ideas? – Tricertops Feb 12 '19 at 12:54