conorgriffin
conorgriffin

Reputation: 4339

Why doesn't the toolbar and search bar show in NavigationStack?

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

The result looks like this NavigationSplitView with .searchable()

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

NavigationStack with .searchable()

Am I doing something wrong? How can I make the search bar appear with NavigationStack in the toolbar the way it does for NavigationSplitView?

Upvotes: 0

Views: 174

Answers (1)

RelativeJoe
RelativeJoe

Reputation: 5104

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

Upvotes: 1

Related Questions