English 中文(简体)
如何使用SwiftUI在MenuBarExtra中添加搜索栏
原标题:How can I add a SearchBar in MenuBarExtra with SwiftUI

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()
        }
    }
}

我希望搜索栏可以显示在菜单栏中

The solution:

@main
struct AppWithMenuBarExtra: App {
    @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true
    @State var searchText: String
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        MenuBarExtra(
            "App Menu Bar Extra", systemImage: "star",
            isInserted: $showMenuBarExtra)
        {
            
            //NavigationLink {
              // Text("Search")
            //}.searchable()
            TextField("Input the search text",text: $searchText)
              .onSubmit { //do search action }
        }
          .menuBarExtraStyle(.window)//add the extra style 
    }
}
问题回答

我已经解决了这个问题,这是我的解决方案:

我们无法将NavigationLink及其协议searchable添加到MenuBarExtra视图中以添加搜索视图,但我们可以在将修饰符.menuBarExtraStyle设置为.window的同时,在MenuBarExtra中添加类似searchBar的TextField

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




相关问题
SwiftUI: How do I position a button x points above a sheet?

I am trying to recreate a Maps-style UI with a persistent bottom sheet and controls fixed above. Apple Maps UI with controls above ☝️ Example here, the "Look Around" binoculars button and ...

How to access own window within SwiftUI view?

The goal is to have easy access to hosting window at any level of SwiftUI view hierarchy. The purpose might be different - close the window, resign first responder, replace root view or ...

热门标签