【问题标题】:Maintaining Sub-Menus in NSPopUpButton在 NSPopUpButton 中维护子菜单
【发布时间】:2012-06-23 09:19:27
【问题描述】:

我正在使用以下绑定对 NSPopUpButton 进行排序:

[arrayController bind:@"contentArray" toObject:self withKeyPath:@"displayElements" options:nil];
[popUpButton bind:@"content" toObject:arrayController withKeyPath:@"arrangedObjects" options:nil];
[popUpButton bind:@"contentValues" toObject:arrayController withKeyPath:@"arrangedObjects.title" options:nil];

其中 displayElements 是 NSMenuItem 的 NSMutable 数组

displayElements = [[NSMutableArray alloc] initWithObjects:[[NSMenuItem alloc]initWithTitle:@"one" action:nil keyEquivalent:@""],
                                                              [[NSMenuItem alloc]initWithTitle:@"two" action:nil keyEquivalent:@""],
                                                              [[NSMenuItem alloc]initWithTitle:@"three" action:nil keyEquivalent:@""],
                                                              nil];

并且排序工作正常。

现在的问题是,如果我将子菜单添加到任何菜单项,然后我将新的 NSMenuItem 添加到数组控制器,则先前添加的子菜单会消失,如下图所示:

在添加新项目之前:

添加新项目后:

我正在使用语句添加一个新的 NSMenuItem:

[arrayController addObject:[[NSMenuItem alloc]initWithTitle:[newItemTextField stringValue] action:nil keyEquivalent:@""]];

当我们对元素进行排序时,会显示相同的行为。 有解决这个问题的想法吗??

【问题讨论】:

  • @Jacob 这是我用来添加子菜单 [[popUpButton menu] setSubmenu:defaultSubMenu forItem:[popUpButton itemAtIndex:[indexValue intValue]]] 的代码,其中 popUpButtonNSPopUpButtonindexValueNSTextField 的一个出口,用户可以从中输入他/她想要添加子菜单的索引。

标签: objective-c cocoa


【解决方案1】:

如果不添加 forItem:[popUpButton itemAtIndex:[indexValue intValue]] 而将其添加到 arrayController 中的项目会发生什么?

我怀疑当您稍后在 ArrayController 中添加菜单项时,绑定会导致 NSPopUpMenu 本身从 NSArrayController 中的值创建新的 NSMenuItems。而数组控制器中的这些项目没有子菜单,因为您直接在弹出按钮中创建了它。

正如您在 Array Controller 中添加新项目一样,我想您应该为 Array Controller 中的项目添加子菜单。

如果当您将子菜单添加到数组控制器中的项目时,您没有看到子菜单出现在按钮本身中,这可能意味着您需要再次触发绑定,以便弹出按钮重新构建其菜单。您可以通过包装将子菜单添加到数组控制器的代码来做到这一点: [arrayController willChangeValueForKey:@"arrangedObjects"];[arrayController didChangeValueForKey:@"arrangedObjects"];

【讨论】:

  • [arrayController willChangeValueForKey:@"arrangedObjects"]; [[[arrayController arrangedObjects]objectAtIndex:[indexValue intValue]]setSubmenu:defaultSubMenu]; [arrayController didChangeValueForKey:@"arrangedObjects"]; 这是你的意思,还是我只是误解了@Jacob
  • 它不工作。但是,正在添加子菜单(我使用 NSLog 打印了 arrayController,我可以看到控制台上添加了一个子菜单)。但子菜单尚未显示在弹出按钮中。有什么想法吗?
  • 如果你对 self 采取类似的方法会发生什么。显示元素?将子菜单更新为 displayElements 项并将其包装在 [self will/didChangeValueForKey:@"displayElements"]
猜你喜欢
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多