I’m building a status bar app and want to call different actions depending on if the user clicked left or right. Here’s what I have so far:
var statusItem = NSStatusBar.system().statusItem(withLength: -1)
statusItem.action = #selector(AppDelegate.doSomeAction(sender:))
let leftClick = NSEventMask.leftMouseDown
let rightClick = NSEventMask.rightMouseDown
statusItem.button?.sendAction(on: leftClick)
statusItem.button?.sendAction(on: rightClick)
func doSomeAction(sender: NSStatusItem) {
print("hello world")
}
My function is not called and I couldn’t find our why. I appreciate any help!
Have you tried:
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
Then seeing which mouse button was pressed in the doSomeAction()
function?
So it will look something like...
let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = statusItem.button {
button.action = #selector(self.doSomeAction(sender:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
}
func doSomeAction(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEventType.rightMouseUp {
// Right button click
} else {
// Left button click
}
}
https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift
Updated: SWIFT 4
I've updated (Craig Francis) answer
func doSomeAction(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp{
// Right button click
} else {
// Left button click
}