如何向 NSPopUpButton(NSMenu) 添加多个具有相同标题的菜单项?
正如文档所说,如果两个菜单项具有相同的标题,则不可能将它们添加到 NSPopUpButton 中。我试图将菜单项添加到 [popupButton 菜单],但没有成功。我还尝试创建一个新菜单,向其中添加项目,然后使用 [popupButton setMenu:newMenu],但没有。菜单始终为每个名称仅显示一项。
但我知道这应该是可能的,如果您尝试在 iTunes 中创建智能播放列表,您可以从左侧弹出按钮中选择“播放列表”,从中间选择“=”,右侧将包含每个播放列表的菜单项iTunes 即使它们具有相同的标题。那么他们是如何做到的呢?
As docs say it's impossible to add two menu items to NSPopUpButton if they both have the same title. I was trying to add menu items to [popupButton menu], but with no luck. I was also trying to create a new menu, add items to it and then use [popupButton setMenu:newMenu], but no. Menu always display only one item per name.
But I know it should be possible, if you try to create a smart playlist in iTunes, you could select "Playlist" from the left popup button, "=" from the middle, and the right one will hold menu items for every playlist in iTunes EVEN if they have the same title. So how do they do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然像 addItemWithTitle: 和 addMenu: 这样的 NSPopUpButton 方法不允许重复名称,但绝对可能有具有相同标题的项目。您只需在 NSMenuItem 本身上设置名称即可。
例如,如果您有一个字符串数组(可能像播放列表名称),您想将它们添加到弹出按钮中,并希望确保其中存在重复项,请按如下操作:
While NSPopUpButton methods like addItemWithTitle: and addMenu: won't allow duplicate names, it is definitely possible to have items with the same title. You simply have to set the name on the NSMenuItem itself.
For example, if you have an array of strings (like playlist names perhaps) you want to add them to a popup button, and want to make sure duplicates will be in there, do it like this:
您可以手动创建 NSMenuItem 并将其直接添加到菜单中,而不是使用
addItemWithTitle:
。这允许您指定所需的任何标题,并能够将其插入菜单中的任何位置。Instead of using
addItemWithTitle:
, you can create an NSMenuItem manually and add it directly to the menu. This allows you to specify any title you want, as well as being able to insert it at any location in the menu.我遇到了确切的问题并且很容易解决。我没有使用 NSPopUpButton 方法(例如 –addItemWithTitle:)来操作按钮项目,而是添加了 NSArrayController 并将项目添加到数组控制器中。然后我使用绑定来绑定控制器和弹出按钮,现在它显示具有相同标题的项目。
要进行绑定:
I had the exact problem and it was solved easily. Instead of using NSPopUpButton methods such as –addItemWithTitle: to manipulate the button items, I added an NSArrayController and added the items into the array controller instead. Then I used the bindings to bind the controller and the popup button and now it shows items with same titles.
To do the bindings:
斯威夫特5
使用保证唯一的标题添加,然后在下一个语句中更改标题。
Swift 5
Add using guaranteed unique title, then alter title in next statement.