How it works
SearchToolbarBehavior describes how a search field that lives in the toolbar presents itself as the user scrolls and interacts with the surrounding content. It lets you opt a searchable view into a more compact, deferential presentation — for example, collapsing the field down to a search icon until it's needed — rather than keeping a full-width search bar permanently on screen. Reach for it when search is a secondary affordance on a content-heavy screen and you want the field to stay out of the way until the user taps it.
Make the view searchable first
SearchToolbarBehavioronly has meaning once a view participates in search, so it builds on thesearchable(text:)modifier. In the example,.searchable(text: $query)binds the search field to thequerystate and is what places a search field into the navigation chrome that the behavior can then style.Apply the behavior with searchToolbarBehavior(_:)
You set the presentation by attaching the
searchToolbarBehavior(_:)modifier to the searchable content, passing aSearchToolbarBehaviorvalue. Here.searchToolbarBehavior(.minimize)requests that the toolbar search field minimize itself, so it occupies less of the bar until the user activates it.Choose a behavior value
The argument is a
SearchToolbarBehaviorinstance, supplied through type-inferred member syntax. The example uses.minimizeto ask the field to collapse toward a compact icon; an.automaticvalue is also available to defer the presentation choice to SwiftUI and the platform's default.Place it inside the navigation container
The behavior governs a search field hosted in toolbar space, so it's applied within a navigation context. In the example the
NavigationStack(with.navigationTitle("Fruits")) provides the bar that the minimized search field lives in, and the modifier sits on theListalongsidesearchable.
.searchToolbarBehavior(.minimize) to .searchToolbarBehavior(.automatic) and watch the search field revert to its standard, non-collapsing presentation.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct SearchToolbarBehaviorDemo: View {
@State private var query = ""
let fruits = ["Apple", "Banana", "Cherry", "Mango"]
var body: some View {
NavigationStack {
List(fruits.filter { query.isEmpty || $0.contains(query) }, id: \.self) { fruit in
Text(fruit)
}
.navigationTitle("Fruits")
.searchable(text: $query)
.searchToolbarBehavior(.minimize)
}
.padding()
}
}