Search code examples
swiftxcodemacosinterface-builder

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


I have a NSPopUpButton with a built up NSMenu.

However, when an NSMenuItem is selected, it keeps going back to the first item.

menu jumping back to default

In this example, I'd expect "Maged" to be selected.

Any ideas?

Related question/answer: https://stackoverflow.com/a/53387962/157656

Duplicate:

It's been suggested that this is a duplicate of the question How do I change/modify the displayed title of an NSPopUpButton

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

However, my question was about getting the NSPopUpButton to show the selected item.


Solution

  • In the end, I changed how I did it.

    I am using a NSButton to show the menu and NSTextField to display the results.

    current implementation

    If anyone is interested in the details, here they are.

    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.

    You need to assign the NSMenu to the NSButton.menu

    Then have a click, something like this.

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

    Your NSMenuItem should have an action on it, which using a selector points to a function.

    Something like this:

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