In the macOS swiftui project I have the following code
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
var statusItem: StatusItem = StatusItem()
func applicationDidFinishLaunching(_ aNotification: Notification) {
}
@objc public func statusBarButtonClicked(sender: NSStatusBarButton) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp {
print("Right click! (AppDelegate)")
} else {
print("Left click! (AppDelegate)")
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
import Cocoa
class StatusItem : NSObject {
private let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
override init() {
super.init()
self.item.button?.title = "title"
self.item.button?.action = #selector(self.statusBarButtonClicked(sender:))
self.item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
@objc public func statusBarButtonClicked(sender: NSStatusBarButton) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp {
print("Right click! (NSObject)")
} else {
print("Left click! (NSObject)")
}
}
}
But when I click NSStatusBarButton it prints "Left click! (AppDelegate)" and "Right click! (AppDelegate)" to console.
Why does it happen? And how to make it call statusBarButtonClicked method defined in StatusItem class?