Search code examples
objective-cmacosdirectorynspopupbutton

Show folders in NSPopUpButton


I want to show folders with icons in my NSPopUpButton. It is common for popups that used for selecting path for file. I'm new user and i can't post images. U can see that for example in U Torrent->preferences->directories

Please provide detailed answer because I'm completely new at that.

Thanks a lot and sorry for my bad English


Solution

  • For each NSMenuItem in your menu, you need to set the appropriate image, calling setImage:

    In short, you need to prepare your menu item, attach it to a menu, and attach the latter to your popup button, like so:

    NSPopUpButton *yourButton = [[NSPopUpButton alloc] init];
    NSMenu *yourMenu = [[NSMenu alloc] init];
    
    NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@"some label" action:nil keyEquivalent:@""];
    NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile:@"yourFilePath"];
    [iconImage setSize:NSMakeSize(16,16)];
    
    [menuItem setImage:iconImage];
    [yourMenu insertItem:menuItem atIndex:0];
    [yourButton setMenu:yourMenu];
    

    Note the use of iconForFile: in NSWorkspace, which allows you to show the same icon used in the Finder.

    For more examples, you can have a look at this sample code by Apple: ButtonMadness