Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>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()
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading