Always show the search bar in a navigation bar in SwiftUI
In this tutorial, we will see how to keep the search bar always visible within the navigation bar.
We can now add a search bar to our navigation views, this simplifies the process of adding search functionality. But in SwiftUI, it’s more difficult to adjust the search bar’s visibility when scrolling.
When we scroll up the content, the search bar will be hidden under the navigation title by default in SwiftUI. It only becomes visible when we scroll down the content. Here, we want to prevent that and make the search bar always visible.
Add a search bar in the navigation bar
First of all, I will create a navigation bar and add a search bar with the searchable()
modifier. Then I will see how the search bar hides when we scroll up the contents.
Example
import SwiftUI struct ContentView: View { @State private var searchBar = "" var body: some View { NavigationView { List { Text("SwiftUI") Text("Python") Text("JavaScript") } .listStyle(.plain) .navigationTitle("CodeSpeedy") } .searchable(text: $searchBar) } }
Output:
Always show the search bar in the navigation bar
Now, to show the search bar always in the navigation bar we can use the placement
parameter within the searchable()
modifier.
We need to simply set the placement
parameter within the searchable()
modifier to .navigationBarDrawer(displayMode: .always)
to achieve this task.
Syntax
placement: .navigationBarDrawer(displayMode: .always)
By adding the above code to the searchable()
modifier we can prevent the search bar from being hidden.
Example
import SwiftUI struct ContentView: View { @State private var searchBar = "" var body: some View { NavigationView { List { Text("SwiftUI") Text("Python") Text("JavaScript") } .listStyle(.plain) .navigationTitle("CodeSpeedy") } .searchable(text: $searchBar, placement: .navigationBarDrawer(displayMode: .always)) } }
Output:
Leave a Reply