将 NSMenuItem 添加到 NSApp.MainMenu 而不是插入新的菜单项

Adding NSMenuItem to NSApp.MainMenu not inserting new menu item

我正在使用以下代码以编程方式添加新菜单项

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

但这并没有添加新的菜单项。

您需要设置 menuItem 子菜单并向其添加新的菜单项,如下所示:

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)
}