How can I add a SearchBar in MenuBarExtra with SwiftUI

233 views Asked by At

macOS 13.0+, Apple introduce a new api named MenuBarExtra which can add a menubar in macOS. But I can't add a searchable protocol into the content to add a search view ?

@main
struct AppWithMenuBarExtra: App {
    @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        MenuBarExtra(
            "App Menu Bar Extra", systemImage: "star",
            isInserted: $showMenuBarExtra)
        {
            NavigationLink {
               Text("Search")
            }.searchable()
        }
    }
}

I expect a search bar can show in the menuBar

1

There are 1 answers

1
Duke On

I have solved this problem, here is my solution:

We can not add a NavigationLink and its protocol searchable into a MenuBarExtra scene for adding a search view, but we can add a TextField as a searchBar in MenuBarExtra when we set the modifier .menuBarExtraStyle to .window:

@main
struct AppWithMenuBarExtra: App {
    @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true
    @State private var searchText: String
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        MenuBarExtra(
            "App Menu Bar Extra", systemImage: "star",
            isInserted: $showMenuBarExtra) {
            TextField("Input the search text",text: $searchText)
              .onSubmit {
            // do search action
            }
        }
        .menuBarExtraStyle(.window) // open item as popover window
    }
}