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

发布于 2025-01-12 04:31:18 字数 247 浏览 1 评论 0原文

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

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

但这不会添加新的菜单项。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ヅ她的身影、若隐若现 2025-01-19 04:31:18

您需要设置 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)
}

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)
}
残疾 2025-01-19 04:31:18
class AppDelegate: NSObject, NSApplicationDelegate, NSToolbarDelegate {
  func applicationDidFinishLaunching(_ notification: Notification) {
    let app = NSApplication.shared
    app.mainMenu = app.customMenu
    app.delegate = self
  }
}
class AppDelegate: NSObject, NSApplicationDelegate, NSToolbarDelegate {
  func applicationDidFinishLaunching(_ notification: Notification) {
    let app = NSApplication.shared
    app.mainMenu = app.customMenu
    app.delegate = self
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文