如何使用 NSMenu 在 NSPopover 中选择 NSMenuItem?

How do I keep NSMenuItem selected in a NSPopover with NSMenu?

我有一个带有内置 NSMenu 的 NSPopUpButton。

但是,当一个 NSMenuItem 被选中时,它会一直返回到第一个项目。

在这个例子中,我希望 "Maged" 被选中。

有什么想法吗?

相关question/answer:

重复:

有人认为这是问题的重复

"I would like an NSPopUpButton to display a different title than the title of the menu item that is selected."

但是,我的问题是关于让 NSPopUpButton 显示所选项目。

最后,我改变了做法。

我正在使用 NSButton 显示菜单并使用 NSTextField 显示结果。

如果有人对细节感兴趣,请看这里。

构建菜单并使用 .representedObject 存储您需要在另一端访问的任何内容。我使用了一个带有名称的结构并在其中编码。

您需要将 NSMenu 分配给 NSButton.menu

然后点一下,像这样。

@IBAction func changeVoiceClicked(_ sender: NSButton)
{
    if let event = NSApplication.shared.currentEvent {
        NSMenu.popUpContextMenu(sender.menu!, with: event, for: sender)
    }
}

你的 NSMenuItem 应该有一个动作,它使用一个选择器指向一个函数。

像这样:

@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.
}