I’m trying to understand how to add a search bar to a NavigationStack using .searchable in SwiftUI.
The documentation states:
Add a search interface to your app by applying one of the searchable view modifiers — like searchable(text:placement:prompt:) — to a NavigationSplitView or NavigationStack, or to a view inside one of these. A search field then appears in the toolbar. The precise placement and appearance of the search field depends on the platform, where you put the modifier in code, and its configuration.
It works in NavigationSplitView with this code:
import SwiftUI
struct ContentView: View {
@State var searchText = ""
var body: some View {
NavigationSplitView {
List {
Text("Option A")
Text("Option B")
}
} detail: {
Text("My App Content")
}
.searchable(text: $searchText, placement: .toolbar)
.padding()
}
}
However it does not work with NavigationStack using code like this
import SwiftUI
struct ContentView: View {
@State var searchText = ""
var body: some View {
NavigationStack {
Text("My App Content")
}
.searchable(text: $searchText, placement: .toolbar)
.padding()
}
}
this results in the following appearance
Am I doing something wrong? How can I make the search bar appear with NavigationStack in the toolbar the way it does for NavigationSplitView?
>Solution :
You need to embed the searchable modifier inside the NavigationStack:
struct ContentView: View {
@State var searchText = ""
var body: some View {
NavigationStack {
Text("My App Content")
.searchable(text: $searchText, placement: .toolbar)
}
.padding()
}
}

