0

我有一个配置了绑定和核心数据的 NSPopUpButton。一切正常,但是我想添加一个实现“编辑列表”操作的项目,比如

Item 1
Item 2
Item 3
Item 4
------
Edit List..

这可能与绑定有关吗?

我认为答案是否定的,至少不完全是。我以为我会以编程方式向按钮提供内容并维护Selected Value的绑定,所以这就是我想出的

- (void)updateSectorPopupItems
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Sector"];
    NSSortDescriptor *sortPosition = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES];

    [request setSortDescriptors:@[sortPosition]];

    NSError *anyError = nil;
    NSArray *fetchObjects = [_gdcManagedObjectContext executeFetchRequest:request
                                                                    error:&anyError];
    if (fetchObjects == nil) {
        DLog(@"Error:%@", [anyError localizedDescription]);
    }

    NSMutableArray *sectorNames = [NSMutableArray array];
    for (NSManagedObject *sector in fetchObjects) {
        [sectorNames addObject:[sector valueForKey:@"sectorCatagory"]];
    }

    [_sectorPopUpBotton addItemsWithTitles:sectorNames];
    NSInteger items = [[_sectorPopUpBotton menu] numberOfItems];

    if (![[_sectorPopUpBotton menu] itemWithTag:1] ) {
        NSMenuItem *editList = [[NSMenuItem alloc] initWithTitle:@"Edit List..." action:@selector(showSectorWindow:) keyEquivalent:@""];
        [editList setTarget:self];
        [editList setTag:1];
        [[_sectorPopUpBotton menu] insertItem:editList atIndex:items];
}

我遇到的几个问题

1)当使用添加菜单项时

[_sectorPopUpBotton menu] insertItem:editList atIndex:items]; 

无论在 atIndex 中输入什么值,该项目始终出现在菜单列表的顶部。

2)我只想让“编辑列表...”菜单项启动操作,如何防止它被选为值?

4

1 回答 1

0

您也可以使用 NSMenuDelegate 方法来做到这一点。

实际上,通过这种方式,您还可以保留用于获取 NSPopUpButton 内容对象的绑定(在您的情况下,从 NSArrayController 绑定到 CoreData 堆栈)。

1) 将对象设置为 NSPopUpButton 内部菜单的委托,您可以在 Interface Builder 中通过向下钻取 NSPopUpButton 以显示其内部菜单来执行此操作。选择它,然后在 Connections Inspector 面板中将其委托设置为您为此任务指定的对象。作为这样的委托,您可以例如提供相同的 ViewController 对象来管理 NSPopUpButton 所在的视图。然后,您需要让作为委托提供的对象遵守 NSMenuDelegate 非正式协议。

2) 实现 NSMenuDelegate 方法 menuNeedsUpdate:除了已由 NSPopButton 绑定获取的那些之外,您将在此处添加要提供的 NSmenuItem(s)(以及最终的分隔符)。一个示例代码是:

#pragma mark NSMenuDelegate
- (void)menuNeedsUpdate:(NSMenu *)menu {
    if ([_thePopUpButton menu] == menu && ![[menu itemArray] containsObject:_editMenuItem]) {
        [menu addItem:[NSMenuItem separatorItem]];
        [menu addItem:_editMenuItem];
    }
}

在此示例中,_editMenuItem 是由实现此 NSMenuDelegate 方法的对象提供的 NSMenuItem 属性。最终它可能是这样的:

_editMenuItem = [[NSMenuItem alloc] initWithTitle:@"Edit…" action:@selector(openEditPopUpMenuVC:) keyEquivalent:@""];
// Eventually also set the target for the action: where the selector is implemented.
_editMenuItem.target = self;

然后,您将实现方法 openEditPopUpMenuVC: 向用户呈现负责编辑 popUpButton 内容的视图(在您的情况下是通过绑定提供的 CoreData 对象)。

我还没有用这种方法解决的唯一问题是,当从编辑发生的视图返回时,NSPopUpButton 将选择新项目“编辑...”,而不是另一个“有效”项目,这非常不方便.

于 2016-11-06T17:24:18.853 回答