Why is my Macos Menu Bar App not showing?

Viewed 46

I'm trying the easiest thing in the book: create an applet for the top menu bar; some kind of status indicator. However, I've been through 3 tutorials and nothing does it: the app compiles but will not show anything in the menu bar. Here is the code:

import SwiftUI 

@NSApplication
class AppDelegate: NSObject, NSApplicationDelegate {
    var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        self.statusItem.button?.title = "TEST"
    }
}

As I said, nothing but the name of my App shows in the menu bar. And I still don't know how to get an output (I just need a print statement to work)

1 Answers

For a minimal reproducible Menu Bar App in Swift:

import SwiftUI 

@main
struct <your-app>: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        Settings {
            EmptyView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    static pricate(set) var instance: AppDelegate!
    lazy var statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

    // Define your menu here (out of scope for this question)
    // let menu = ApplicationMenu()    <-- define ApplicationMenu() 

    func applicationDidFinishLaunching(_ notification: Notification) {
        AppDelegate.instance = self 
        
        // Define the Menu Bar Icon as Text 
        statusBarItem.button?.title = "hello world"

        // Enable your Menu (out of scope)
        // statusBarItem.menu = menu.createMenu()    <-- define createMenu()
    }
}

Compile and Run, you should see a nice little 'hello world' next to your battery status icon.

Out of Scope To add a menu to this MacOs Top Bar Applet app you'll need a new ApplicationMenu class with a createMenu() function.

Related