How do I add a menu bar command in Swift

Asked on 2024-07-29

1 search

To add a menu bar command in Swift, you can use SwiftUI menus in AppKit contexts by leveraging the NSHostingMenu, which is a new NSMenu subclass. Here’s a step-by-step guide on how to do this:

  1. Create Your Menu Definition: Define your menu using a SwiftUI view. Use SwiftUI views that best describe the data relationship, such as toggles, pickers, and buttons.

  2. Initialize NSHostingMenu: Initialize an NSHostingMenu with your SwiftUI view.

  3. Use in AppKit Contexts: Use the NSHostingMenu in any AppKit context that accepts an NSMenu, such as the new NSPopupButton initializer with a pull-down menu parameter.

Here is a code example to illustrate this:

import SwiftUI
import AppKit

struct MyMenu: View {
    var body: some View {
        Menu {
            Button("Action 1", action: performAction1)
            Button("Action 2", action: performAction2)
            Toggle("Toggle Option", isOn: $toggleOption)
            Picker("Pick an Option", selection: $selectedOption) {
                Text("Option 1").tag(1)
                Text("Option 2").tag(2)
            }
        } label: {
            Text("My Menu")
        }
    }
    
    @State private var toggleOption = false
    @State private var selectedOption = 1
    
    func performAction1() {
        // Action 1 code
    }
    
    func performAction2() {
        // Action 2 code
    }
}

let menu = NSHostingMenu(rootView: MyMenu())

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