我试图通过使用NSMenu类通过Appkit添加一个菜单到应用程序菜单。但我不确定如何称呼它,到目前为止,我试过了:
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
var menu: NSMenu!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 512),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
class myMenu: NSMenu {
init(aTitle: "HelloWorld")
}
}
但是这只给了我"预期参数类型后面的':'"one_answers"'必需的'初始化器'init(coder:)'必须由'NSMenu'的子类提供"
我为buildnd和buildMenu使用了单独的函数,但这应该可以使用您的技术。在你的swift项目中创建一个名为main.swift的新文件,并删除已有的AppDelegate。将这些代码复制/粘贴到main.swift文件中。
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
// var menu: NSMenu!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
// let contentView = ContentView()
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 512),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
window.center()
window.setFrameAutosaveName("Main Window")
// window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
let mainMenu = NSMenu()
NSApp.mainMenu = mainMenu
// **** App menu **** //
let appMenuItem = NSMenuItem()
mainMenu.addItem(appMenuItem)
let appMenu = NSMenu()
appMenuItem.submenu = appMenu
appMenu.addItem(withTitle:"Quit", action:#selector(NSApplication.terminate), keyEquivalent: "q")
}
}
let appDelegate = AppDelegate()
// **** Main **** //
let application = NSApplication.shared
application.delegate = appDelegate
//application.activate(ignoringOtherApps:true)
application.run()