1

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?

Warren Burton
  • 17,451
  • 3
  • 53
  • 73
bapafes482
  • 444
  • 4
  • 18

1 Answers1

3

Setting the button's action is only one half of what you need to do. You also need to specify a target. Add

 self.item.button?.target = self 

and I believe you will get the result you are looking for.

What's happening is action specifies the selector to invoke and target specifies the object on which to invoke it.

idz
  • 12,825
  • 1
  • 29
  • 40