Grant Wilkinson
Grant Wilkinson

Reputation: 1128

Setting Actions for PopUpButton

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");

}

Upvotes: 2

Views: 5174

Answers (2)

Evan Mulawski
Evan Mulawski

Reputation: 55334

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.

Upvotes: 4

Keith Smiley
Keith Smiley

Reputation: 63903

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.

Upvotes: 3

Related Questions