1

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

Fatso
  • 1,278
  • 16
  • 46

1 Answers1

4

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];
}
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • I'll try this and report back (and will pick as best answer if it works). Thank you already for the trouble!!! – Fatso Sep 18 '12 at 16:26
  • It works when I work with a popup button and use your code. Thanks man! – Fatso Sep 18 '12 at 17:20
  • Thanks for this, it was driving me absolutely barmy trying to work out why the title wasn't changing! The truly annoying thing is I've gone over the documentation for NSPopupButton several times and I did not see the quote you mention anywhere. – Ash Jul 24 '16 at 09:16