Create a Search Bar in a List in SwiftUI
Written by Team Kodeco
Adding a search bar to a list in SwiftUI can significantly enhance the user experience by allowing users to quickly find specific items. This is particularly beneficial when dealing with longer lists. In this entry, you’ll learn how to implement a search bar in a list using SwiftUI.
First, you will establish a state variable to hold the search text entered by the user, like so:
@State private var searchText = ""
You’ll then proceed to add the search bar to your list. You achieve this by inserting it as the header of the list using the searchable
modifier:
struct Park: Identifiable {
let id = UUID()
let name: String
}
struct ContentView: View {
@State private var searchText = ""
let parks: [Park] = [
Park(name: "Yosemite National Park"),
Park(name: "Redwood National and State Parks"),
Park(name: "Sequoia National Park"),
Park(name: "Pinnacles National Park"),
Park(name: "Joshua Tree National Park"),
Park(name: "Death Valley National Park"),
Park(name: "Channel Islands National Park"),
Park(name: "Kings Canyon National Park"),
Park(name: "Lassen Volcanic National Park"),
Park(name: "Point Reyes National Seashore")
]
var body: some View {
NavigationStack {
List {
ForEach(parks.filter { searchText.isEmpty || $0.name.localizedCaseInsensitiveContains(searchText) }) { park in
Text(park.name)
}
}
.navigationTitle("California Parks")
.searchable(text: $searchText)
}
}
}
Your preview should look like this:
In this example, you have a list of California national parks. You add a search bar to the list using the searchable
modifier, and the text
parameter is bound to our searchText
state variable using SwiftUI’s $ syntax to indicate a two-way binding. This ensures that searchText
updates as the user types into the search bar.
The list items are then filtered based on the search text entered by the user. This is accomplished by adding a filter to the list items.
By incorporating a search bar in your SwiftUI list, users can swiftly locate items of interest. This significantly enhances user-friendliness and efficiency. Try it out in your own app today!