-1

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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
techno
  • 6,100
  • 16
  • 86
  • 192

1 Answers1

1

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)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Thanks for the answer.This adds the new Menu item but when i use this piece of code,the Main View becomes empty ie: none of the controls in it are displayed and it shrinks. – techno Mar 05 '22 at 08:12
  • 1
    i think its because of some indexing issue as you have hardcoded `7` in code to add the sub menu item.When this piece of code is removed it works as expected. – techno Mar 05 '22 at 08:14