swiftmacosnsmenunsmenuitemnsapplication

Adding NSMenuItem to NSApp.MainMenu not inserting new menu item


I'm using the following code to add a new menu item programatically

override func viewDidLoad() {
    let mainMenu = NSApp.mainMenu
    let myMenu = NSMenuItem(title: "MenuTitle", action: nil, keyEquivalent: "")
    mainMenu!.addItem(myMenu)
}

But this does not add a new menu item.


Solution

  • You need to set your menuItem submenu and add new menu items to it as follow:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let menuItem = NSMenuItem(title: "SubMenu", action: nil, keyEquivalent: "")
    
        let subMenu = NSMenu(title: "SubMenu")
        subMenu.addItem(withTitle: "abc", action: #selector(abc), keyEquivalent: "")
    
        menuItem.submenu = subMenu
    
        NSApp.mainMenu?.addItem(menuItem)
    }
    
    @objc func abc(_ menuItem: NSMenuItem) {
        print(#function)
    }