Question

I'm using this code to add a popup button to an NSView :

if (popupButton) [popupButton release];
popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(0, 0, SHEET_WIDTH/2, 32) pullsDown:true];
NSMenu *menu = [[NSMenu alloc] init];
for (NSString *title in anArray)
    [menu addItemWithTitle:title action:NULL keyEquivalent:@""];
[popupButton setMenu:menu];
[self addView:popupButton aligned:KOAlignmentCenter];

When I launch my app, the button has no selection. When the user clicks on it and selects one of the items, the button remains empty. For example, if there are 3 possible selections (item1, item2 & item3), and the user clicks on the second one, instead of showing 'item2' it shows nothing :

empty selection

Was it helpful?

Solution

I don't know why you're not getting anything showing up, because when I tried your code, I did get the first item in anArray to show up. However, picking an item from the list doesn't change what's displayed, and that is the expected behavior for a pull down type of button. From Apple's docs:

Pulldown lists typically display themselves adjacent to the popup button in the same way a submenu is displayed next to its parent item. Unlike popup lists, the title of a popup button displaying a pulldown list is not based on the currently selected item and thus remains fixed unless you change using the cell’s setTitle: method.

You also don't need either of the menu statements, you can just use the NSPopupButton method, addItemWithTitle:, in your loop. So try it without the menu commands, and use setTitle: explicitly, if you still don't get anything showing initially. Or, you could change to a popup instead of pull down, then you don't have the problem of setting the title.

This is what I did to test:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    NSArray *anArray = @[@"One",@"Two",@"Three",@"Four"];
    _popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(100, 200, 200, 32) pullsDown:TRUE];
    for (NSString *title in anArray)
        [_popupButton addItemWithTitle:title];
    [self.window.contentView addSubview:_popupButton];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top