Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action of StatusItem not working in Swift

Tags:

macos

swift

cocoa

So I am a newbie to Swift and wanted to create a simple example status bar app on MacOS. To keep things clean I created a subclass App which is creating the status item. This class is then created in the applicationDidFinishLaunching function of the AppDelegate.swift.

But somehow nothing is printed on the console when I press the status icon. However if I copy the code in the AppDelegate file it works. Does someone know what I am doing wrong and why it is not working in the subclass?

Here is the code of my own class:

import Cocoa

class App: NSObject {

    let menuBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

    override init() {
        print("created app instance");

        if let button = menuBarItem.button {
            button.image = NSImage(named: NSImage.Name("StatusBarButtonImage"))
            button.action = #selector(test(_:))
        }
    }

    @objc func test(_ sender: Any?) {
        print("button was pressed")
    }
}

and the AppDelegate:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var appInstance: App!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        appInstance = App()
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}
like image 464
D0miH Avatar asked Mar 06 '23 10:03

D0miH


1 Answers

If the button is showing up and nothing is happening when you click it, it looks to me like you need to make sure you're setting your button's target to your App instance. E.g.:

button.target = self

Otherwise the action is only followed up the responder chain.

like image 190
Wevah Avatar answered Mar 09 '23 06:03

Wevah