Devapploper Devapploper - 4 months ago 28
Swift Question

Call Action when NSStatusBarButton is right-clicked

I am searching for a way to detect whenever the

NSStatusBarButton
is right-clicked (using Swift) and call an action.

I am currently setting it up this way:

let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)

func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
if let button = statusItem.button {
button.image = NSImage(named: "myImage")
button.alternateImage = NSImage(named: "myImage")
button.action = Selector("myAction")
}
}


I thought of using the
button.rightMouseDown(<#theEvent: NSEvent#>)
(Because there is no such "alternateAction") but unfortunately I did not manage to come up with something due to the fact that I just started programming Mac apps.


Update:



While searching for a way to do this I saw some threads telling to subclass a
NSView
but I don't se how this should work (This could be because I am really new to programming and don't even know how to "subclass"). Still I thought there was some easier way to use this since nearly every
statusBar
App that I know rects on right-clicks.

Answer

You can subclass and override the mouseDown method, but since Mac OS X 10.10 (Yosemite), there has been an easier way: NSGestureRecognizer and its subclasses:

func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application
    if let button = statusItem.button {
        button.image = NSImage(named: "myImage")
        button.alternateImage = NSImage(named: "myImage")
        button.action = Selector("myAction")

        // Add right click functionality
        let gesture = NSClickGestureRecognizer()
        gesture.buttonMask = 0x2 // right mouse
        gesture.target = self
        gesture.action = "myRightClickAction:"
        button.addGestureRecognizer(gesture)
    }
}

func myRightClickAction(sender: NSGestureRecognizer) {
    if let button = sender.view as? NSButton {
        // Handle your right click event here
    }
}