Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to group items in a NSPopupButton?

I'm trying to display a list of system voices, but I'd like to group them by region.

This is an example of select in html.

Drop down menu with grouped items

Ideally I'd like to create a dropdown that is similar to accessibility language selection.

enter image description here

Is there any way to replicate this in Interface Builder / swift? Any pointers would be appreciated.

Update:

The reason for this, is because I am displaying a list of speech voices to the user. At the moment, it mixes all the regions together, which is very confusing.

voice drop down

There is an update I'm working on, where I can display "English (United Kingdom)", but I'd like to group them up before releasing it.

like image 608
Daniel P Avatar asked Dec 21 '25 22:12

Daniel P


1 Answers

The following code groups menu, but not like the way you mentioned.

let items = [["First","Second"],["First","Second"],["First","Second"]]

lazy var addNewViewButton : NSPopUpButton = {
    let popupButton = NSPopUpButton()

    let firstMenuItem = NSMenuItem(title: "First Group", action: nil, keyEquivalent: "")
    let secondMenuItem = NSMenuItem(title: "Second Group", action: nil, keyEquivalent: "")
    let thirdMenuItem = NSMenuItem(title: "Third Group", action: nil, keyEquivalent: "")

    let superMenu = NSMenu()
    superMenu.addItem(firstMenuItem)
    superMenu.addItem(secondMenuItem)
    superMenu.addItem(thirdMenuItem)

    for (index,item) in items.enumerated()
    {
        let menu = NSMenu()
        for title in item
        {
            let menuItem = NSMenuItem(title: title, action: nil, keyEquivalent: "")
            menuItem.target = self
            menu.addItem(menuItem)
        }
        menu.addItem(NSMenuItem.separator())
        superMenu.setSubmenu(menu, for: superMenu.items[index])
    }
    popupButton.menu = superMenu

    popupButton.translatesAutoresizingMaskIntoConstraints = false

    return popupButton
}()

Add the popupbutton in your code and you will get results like this

enter image description here

Each one will be having its own items inside.

like image 57
mouseymaniac Avatar answered Dec 24 '25 12:12

mouseymaniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!