The .searchable()
searchbar isn't showing when you push a view, only in a modal. Is this intentional by Apple or am I implementing it incorrectly?
Video and code below:
Home View:
struct ContentView: View {
@State private var showSearchView = false
var body: some View {
NavigationStack {
VStack {
NavigationLink(
destination: SearchView()
) {
Text("Push Search View")
}
.buttonStyle(.borderedProminent)
.clipShape(Capsule())
Button {
showSearchView = true
} label: {
Text("Modal Search View")
}
.buttonStyle(.borderedProminent)
.clipShape(Capsule())
}
.navigationTitle("Home")
}
.sheet(isPresented: $showSearchView) {
SearchView()
}
}
}
Search View
struct SearchView: View {
@State private var searchText = ""
var body: some View {
NavigationStack {
Text("Searching for \(searchText)")
.navigationTitle("Searchable Example")
}
.searchable(text: $searchText, prompt: "Look for something")
}
}
It is best to have one NavigationStack
in a flow instead of creating a new one each time you push a View
using NavigationLink
.
However, it's worth noting that when you use the .searchable
modifier within the stack, the search bar appears normally:
struct SearchView: View {
@State private var searchText = ""
var body: some View {
NavigationStack {
Text("Searching for \(searchText)")
.navigationTitle("Searchable Example")
.searchable(text: $searchText, prompt: "Look for something")
}
}
}