lutrekubej lutrekubej - 7 months ago 417
Swift Question

Swift 2.2 selector in NSMenuItem

I have a simple one file menu bar app in swift:

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


I can't make the "About" menu bar item to connected to the about() function. When I run the app, the "About" item is disabled.

How do I pass the selector to menu item action in Swift 2.2? Thanks

Answer

The selector is supposed to have a parameter (the NSMenuItem instance)

aboutMenuItem.action = #selector(StatusBarApp.about(_:))

...

func about(sender : NSMenuItem) {
   print("XXX")
}

Edit:

The solution is to run the app as full Cocoa app including its delegate.
I added a second menu item to terminate the app.

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()
Comments