Search code examples
swiftnsmenuitem

NSMenuItem updating title


I'm able to programmatically create menu items using the following code.

primaryMenu.addItem(NSMenuItem(title: "MenuTitle", action: nil, keyEquivalent: ""))

I want to be able to update the title from this menu item. I have been able to do it very easily when I manually create the menu using Interface Building.

I don't have a way to identify the menu item.


Solution

  • Store a reference to your NSMenuItem (such as in an instance variable), and set the title on it whenever you wish:

    let myMenu = NSMenuItem(title: "MenuTitle", action: nil, keyEquivalent: "")
    
    primaryMenu.addItem(myMenu)
    
    //somewhere else:
    myMenu.title = "xyz"