Search code examples
macoscocoansmenunsmenuitemnspopupbutton

Straightforward way to implement custom drawn NSMenuItem views


I would like to have a NSMenu with several NSMenuItems in it. Those items shall behave just like "normal" NSMenuItems, with one exception: I would like to be able to draw the contents (i.e. the "foreground") of each item on my own.

That is:

  • I would like the operating system to draw the blue highlight when I hover with the mouse, draw the checkmark or dash (to signify "selected"/"part of multi-selection"). Moreover, I would like "normal", i.e. menu-built-in mouse/keyboard behaviour.

  • I would like to draw the "contents" myself: Ideally, I would imagine that I would have to implement/override one single method drawMenuItem:withCGContext:inRectangle:withTextColor, which basically obtains the item, the CGContext to draw into, the NSRect of the item, and the text color that would be used by Mac OS if it drew the item itself.

I know (suspect very stronlgy) that my wish is probably too much, but I would be perfectly fine with something adequate (e.g. I could imagine fetching the NSRect from the NSMenuItem myself, obtaining the color using something like [NSColor selectedMenuItemTextColor], and the context using something like [NSContext currentContext]).

Of course I considered Apple's instruction on this. However, doing this prevents the menu from drawing the blue highlight background and the check mark. Moreover, as far as I could see, I would have to implement e.g. mouseUp myself.

To sum it up: Is there a way to get a (almost) fully functional menu, where I only customize the contents where usually the menu item title goes (possibly even without custom views)?


Solution

  • The answer is: No.

    Since you are replacing the entire view of the menu item you are responsible for the drawing and to handle the events.