How do I add a menu bar command in SwiftUI

Asked on 07/29/2024

1 search

To add a menu bar command in SwiftUI, you can use the new NSHostingMenu class introduced in macOS Sequoia. This allows you to define your menu using SwiftUI views and integrate it seamlessly with AppKit contexts. Here’s a step-by-step guide:

  1. Create your menu definition using a SwiftUI view:

    • Use SwiftUI views like Toggle, Picker, and Button to define the menu items.
  2. Initialize an NSHostingMenu with the SwiftUI view:

    • This new NSMenu subclass allows you to use SwiftUI menus in AppKit contexts.
  3. Use the NSHostingMenu in any AppKit context that accepts an NSMenu:

    • For example, you can use it with the new NSPopupButton initializer that accepts a pull-down menu parameter.

Here is a code snippet to illustrate this:

import SwiftUI
import AppKit

struct MyMenuView: View {
    @State private var isToggled: Bool = false

    var body: some View {
        VStack {
            Toggle("Toggle Option", isOn: $isToggled)
            Picker("Select Option", selection: $isToggled) {
                Text("Option 1").tag(true)
                Text("Option 2").tag(false)
            }
            Button("Perform Action") {
                // Action code here
            }
        }
    }
}

let menu = NSHostingMenu(rootView: MyMenuView())
let menuItem = NSMenuItem()
menuItem.submenu = menu
NSApp.mainMenu?.addItem(menuItem)

For more details, you can refer to the session What’s new in AppKit at the 06:41 mark.