In Swift 5,
I worked this way.
I was able to detect whether it was a right click or a left click from refering to the above answer.
However, once you right click, you can only display the NSMenu all the time.
Then, I add statusItem.button?.performClick(nil)
& statusItem?.menu = nil
You can add statusItem?.popUpMenu(menu)
, but it's depreciated in macOS 10.14. (But it worked well.)
Finally, if left click, it runs a function. And if right click, it runs menu items like Quit.
Thank you to those who answered earlier !
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishedLaunching(_ notification: Notification) {
// .....
// .....
if let button = statusItem?.button {
button.image = NSImage(named: "iconImage")
button.action = #selector(self.statusBarButtonClicked(_:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
// Add Menu Item for NSMenu
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
}
@objc func statusBarButtonClicked(_ sender: NSStatusBarButton) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp {
print("Right Click")
statusItem?.menu = menu
statusItem?.button?.performClick(nil)
// statusItem?.popUpMenu(menu)
statusItem?.menu = nil
} else {
print("Left Click")
togglePopover(sender)
}
}
}