问题描述
我有一个带有内置NSMenu的NSPopUpButton.
I have a NSPopUpButton with a built up NSMenu.
然而,在选择了NSMenuItem时,它一直回到第一项.
However, when an NSMenuItem is selected, it keeps going back to the first item.
在此示例中,我希望选择"Maged".
In this example, I'd expect "Maged" to be selected.
有什么想法吗?
相关问题/答案: https://stackoverflow.com/a/53387962/157656
重复:
有人建议这是问题的重复如何更改/修改NSPopUpButton
It's been suggested that this is a duplicate of the questionHow do I change/modify the displayed title of an NSPopUpButton
我希望NSPopUpButton显示与所选菜单项的标题不同的标题."
"I would like an NSPopUpButton to display a different title than the title of the menu item that is selected."
但是,我的问题是关于让NSPopUpButton显示所选项目.
However, my question was about getting the NSPopUpButton to show the selected item.
推荐答案
最后,我更改了操作方式.
In the end, I changed how I did it.
我正在使用NSButton来显示菜单,并使用NSTextField来显示结果.
I am using a NSButton to show the menu and NSTextField to display the results.
如果有人对这些细节感兴趣,就在这里.
If anyone is interested in the details, here they are.
建立菜单,并使用.representedObject来存储您需要在另一端访问的所有内容.我使用了一个带有名称的结构,并在其中进行了编码.
Build the menu up and use .representedObject to store whatever you need to access at the other end. I used a struct with the name and code the in it.
您需要将NSMenu分配给NSButton.menu
You need to assign the NSMenu to the NSButton.menu
然后单击,类似这样.
@IBAction func changeVoiceClicked(_ sender: NSButton)
{
if let event = NSApplication.shared.currentEvent {
NSMenu.popUpContextMenu(sender.menu!, with: event, for: sender)
}
}
您的NSMenuItem应该对其执行操作,该操作使用选择器指向一个函数.
Your NSMenuItem should have an action on it, which using a selector points to a function.
类似这样的东西:
@objc func voiceChanged(sender: NSMenuItem)
{
// cope will nil
var voice : VoiceDetail = VoiceDetail();
if (sender.representedObject != nil) {
voice = sender.representedObject as! VoiceDetail;
}
// Do what you need to on menu select.
// update text field.
}
这篇关于如何使用NSMenu在NSPopover中保持选中NSMenuItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!