我在 swift中有一个简单的文件菜单栏应用程序: import Cocoaclass StatusBarApp : NSObject { func buildMenu() { let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) statusItem.title
import Cocoa class StatusBarApp : NSObject { func buildMenu() { let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) statusItem.title = "StatusBarApp" let menu = NSMenu() let aboutMenuItem = NSMenuItem() aboutMenuItem.title = "About" aboutMenuItem.target = self aboutMenuItem.action = #selector(about) menu.addItem(aboutMenuItem) statusItem.menu = menu } func about() { print("XXX") } } NSApplication.sharedApplication() StatusBarApp().buildMenu() NSApp.run()
我无法将“关于”菜单栏项连接到about()函数.当我运行应用程序时,“关于”项目被禁用.
如何将选择器传递给Swift 2.2中的菜单项操作?谢谢
选择器应该有一个参数(NSMenuItem实例)aboutMenuItem.action = #selector(StatusBarApp.about(_:)) ... func about(sender : NSMenuItem) { print("XXX") }
编辑:
解决方案是将应用程序作为完整的Cocoa应用程序运行,包括其委托.
我添加了第二个菜单项来终止应用程序.
import Cocoa class StatusBarApp : NSObject, NSApplicationDelegate { var statusItem : NSStatusItem! func applicationDidFinishLaunching(aNotification: NSNotification) { statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) statusItem.title = "StatusBarApp" let menu = NSMenu() let aboutMenuItem = NSMenuItem(title:"About", action:#selector(StatusBarApp.about(_:)), keyEquivalent:"") aboutMenuItem.target = self let quitMenuItem = NSMenuItem(title:"Quit", action:#selector(StatusBarApp.quit(_:)), keyEquivalent:"") quitMenuItem.target = self menu.addItem(aboutMenuItem) menu.addItem(quitMenuItem) statusItem.menu = menu } func about(sender : NSMenuItem) { print("XXX") } func quit(sender : NSMenuItem) { NSApp.terminate(self) } } NSApplication.sharedApplication() let statusBarApp = StatusBarApp() NSApp.delegate = statusBarApp NSApp.run()