2

I have created an NSPopUpButton programmatically and I made an array for my choices, how can I create a setAction for each individual array choice? Thanks!

NSRect buttonRect = NSMakeRect(1705, 145, 78, 50); 

    //Button Array.  When I pick the choice it closes the diologue box
    NSArray *newArray;
    NSString *color1 = @"Blue Color";
    NSString *color2 = @"Green Color";
    NSString *color3 = @"Clear Color";

    newArray = [NSArray arrayWithObjects: color1, color2, color3, nil];

    NSPopUpButton *button = [[NSPopUpButton alloc] initWithFrame:buttonRect pullsDown:YES];
    [self addSubview:button];
    [button addItemsWithTitles:newArray];
    //want my action for each individual string
    [button setAction:@selector(changeFilterColor)];

-(void) changeFilterColor
{
    NSLog(@"colorChanged");

}
Grant Wilkinson
  • 1,088
  • 1
  • 13
  • 38

2 Answers2

4

You need to add the NSMenuDelegate protocol to your interface (.h file):

@interface MyClass : NSObject <NSMenuDelegate>

Then:

[[button menu]setDelegate:self];

after you create the NSPopUpButton. Also, remove the line with setAction:.

Copy this delegate method:

-(void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item
{
    if ([item.title isEqualToString:@"Blue Color"]) { ... } //etc
}

Add the necessary if statements to complete the comparisons.

lindon fox
  • 3,298
  • 3
  • 33
  • 59
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
3

Another option for this is the use the setAction method you originally had in your code. But then for the selector you choose to call set it up to receive a sender object. Something like this:

-(void)method:(NSMenuItem *)sender

Then you can verify that the sender object is valid and get the title from that instead. I'm a little wary of using NSMenuDelegate for this.

Keith Smiley
  • 61,481
  • 12
  • 97
  • 110