Resolved Change image when NSMenuItem highlights?

Discussion in 'Mac Programming' started by ArtOfWarfare, Jun 9, 2012.

  1. ArtOfWarfare, Jun 9, 2012
    Last edited: Jun 10, 2012

    ArtOfWarfare macrumors 604


    Nov 26, 2007
    Does anyone have any suggestions for how to set up an NSMenuItem to have two images that it alternates between based on whether it's currently highlighted or not?

    The best I have so far is I change the item's image whenever the delegate receives either menuWillOpen or menuDidClose.

    This has two issues, unfortunately:
    1 - There's a slight, but noticeable, delay when the item is highlighted.
    2 - It's possible to have a menu open but not actually highlight the item. (IE, if the item is the first one in the menu, you can move the cursor above the menu. The submenu will remain open, but the highlight will go away. Leaving me with a highlighted icon, but not a highlighted item.)

    I've attempted to subclass NSMenuItem and see if various method names get called ever... (things like setHighlighted:, setIsHighlighted:, isHighlighted) but none work...

    I can't believe how difficult this seems to be. Apple's own built in menus perform this. (Just click on the wi-fi menu and highlight an item. Notice that the various icons change from black to white when you highlight them.)

    2X Edit:
    I've discovered a delegate method, menu:willHighlightItem:, which has proven to be very useful for properly changing an item's image right when it gets highlighted.

    3X Edit:
    The delegate occasionally isn't called when it should be. (The documentation says it gets called with item being nil when all the items are being unhighlighted... but it doesn't if the cursor simply moves back to the supermenu.)

    So... my code looks like this, and since the menuItems with the images that should change back and forth each have submenus, I can just look for when the menu closes.

Share This Page