how do I create a menu bar app

Asked on 2024-08-01

1 search

To create a menu bar app on macOS, you can use SwiftUI and AppKit together. Here are the steps to get you started:

  1. Create a SwiftUI App: Start by creating a new SwiftUI project in Xcode.

  2. Define the Menu: Use SwiftUI to define your menu. You can use NSHostingMenu to integrate SwiftUI menus into your AppKit context. This allows you to share menu definitions between different parts of your app.

    import SwiftUI
    
    struct MyMenu: View {
        var body: some View {
            Menu("My Menu") {
                Button("Action 1", action: performAction1)
                Button("Action 2", action: performAction2)
            }
        }
    
        func performAction1() {
            // Action 1 code
        }
    
        func performAction2() {
            // Action 2 code
        }
    }
    
  3. Integrate with AppKit: Use NSHostingMenu to integrate the SwiftUI menu into your AppKit application.

    import AppKit
    import SwiftUI
    
    class AppDelegate: NSObject, NSApplicationDelegate {
        var statusBarItem: NSStatusItem?
    
        func applicationDidFinishLaunching(_ notification: Notification) {
            let menu = NSMenu()
            let hostingMenu = NSHostingMenu(rootView: MyMenu())
            menu.addItem(withTitle: "My Menu", action: nil, keyEquivalent: "").submenu = hostingMenu
    
            statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
            statusBarItem?.button?.title = "Menu Bar App"
            statusBarItem?.menu = menu
        }
    }
    
  4. Set Up the App Delegate: Ensure your AppDelegate is set up correctly in your @main struct.

    @main
    struct MyApp: App {
        @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    

For more detailed information on integrating SwiftUI with AppKit, you can refer to the session What’s new in AppKit.

Relevant Sessions

  1. What’s new in AppKit
  2. Tailor macOS windows with SwiftUI
  3. Work with windows in SwiftUI

These sessions provide insights into using SwiftUI with AppKit, customizing window behaviors, and refining window placements, which are essential for creating a polished menu bar app.