(Objective C) NSPopUpButton 不更新显示的值

(Objective C) NSPopUpButton not updating displayed value

我正在使用 NSPopUpButton 制作一个 UI,将一个字符串数组传递给它并按索引选择一个项目。然后显示时,它默认为第一项。谁能看到我错过了什么? DropDownView 扩展了一个 NSView。

@implementation DropDownView

- (id)initWithFrame: (NSRect)frameRect
             values: (NSArray<NSString*>*) vals
            current: (NSInteger) currentIndex
{
    [super initWithFrame:frameRect];
    menu = [[NSPopUpButton alloc]initWithFrame:frameRect pullsDown:NO];

    [menu addItemsWithTitles:vals];

    [menu setEnabled:true];

    // this does not change the currently displayed value
    // have tried various combinations of the below
    [menu selectItemAtIndex:currentIndex];
    // [menu selectItemWithTitle:vals[currentIndex]];
    [menu synchronizeTitleAndSelectedItem];

    [self addSubview:menu];

    [menu bind:@"selectedIndex" toObject:self withKeyPath:@"indexOfSelectedItem" options:nil];

    return self;
}
@end

非常感谢!

绑定selectedIndex时,菜单的selectedIndex设置为self.indexOfSelectedItem。不要调用 selectItemAtIndex 和 synchronizeTitleAndSelectedItem 并将 indexOfSelectedItem 设置为 currentIndex。