我已经以编程方式创建了一个NSPopUpButton,并为自己的选择创建了一个数组,如何为每个单独的数组选择创建一个setAction?谢谢!

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

}

最佳答案

您需要将NSMenuDelegate协议添加到您的接口(.h文件):

@interface MyClass : NSObject <NSMenuDelegate>


然后:

[[button menu]setDelegate:self];


创建NSPopUpButton之后。另外,用setAction:删除该行。

复制此委托方法:

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


添加必要的if语句以完成比较。

08-07 10:06