4
votes

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

3
In Swift 4.2, you just need to add @objc func aboutonmyway133

3 Answers

0
votes

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

update action

aboutMenuItem.action = Selector("about")

and add

aboutMenuItem.enabled = true
0
votes

Consider this:

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


let app = StatusBarApp()
NSApplication.sharedApplication()
app.buildMenu()
NSApp.run()