SwiftUI MenuBarExtra with custom view in menubar instead of just icon and label

822 Views Asked by At

I read that one can use MenuBarExtra in a Swift macOS application to create a menubar application. An icon with a label can be displayed in the menubar. However, clicking on the entry opens a context menu that can contain rich content. I'd like to use this easy, convenient and small code but instead of displaying only an icon and a label I need to display a custom view. That view will contain multiple labels in different colors and will get updated continuously. Is this possible with MenuBarExtra? I have no code yet. For example iStat has such a menu.

2

There are 2 best solutions below

0
rob mayoff On

Based on my testing on macOS 13.5.2, you cannot do this with MenuBarExtra. You'll need to use the NSStatusItem API from AppKit.

1
Bahman World On

Use this:

import SwiftUI

@main
struct DesktopTestApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        
        // Add this line ---->
        MenuBarExtra("App", systemImage: "square.stack.3d.down.forward") {
            VStack {
                Text("hello world")
                // your views goes here
            }
            .frame(width: 300, height: 300)
            .background(.windowBackground)
        }.menuBarExtraStyle(.window)
        // ------------------------ 
    }  
}