SwiftUI includes a SearchBar component starting from iOS 15. Start with this code to display a list of vehicles:
struct Vehicle: Identifiable {
var id = UUID()
var name: String
var image: String
}
struct ContentView: View {
var vehicles = [Vehicle(name: "car", image: "car"),
Vehicle(name: "bus", image: "bus"),
Vehicle(name: "tram", image: "tram"),
Vehicle(name: "bicycle", image: "bicycle")]
var body: some View {
ForEach(vehicles) { vehicle in
RowView(vehicle: vehicle)
}
}
}
struct RowView: View {
var vehicle: Vehicle
var body: some View {
HStack {
Image(systemName: vehicle.image)
.resizable()
.frame(width: 60, height: 60)
Text(vehicle.name)
}
}
}
To implement the search we have to do:
- Create a variable to store the search results. (1)
- Create a variable to hold the search text. (2)
- Add a NavigationStack to the view, as the SearchBar will be placed in the navigation bar. (3)
- Add the searchBar to the list (4)
//....
@State private var searchText = "" // 2
var body: some View {
NavigationStack { // 3
List {
ForEach(searchResults) { vehicle in
RowView(vehicle: vehicle)
}.onDelete { (indexSet) in
self.vehicles.remove(atOffsets: indexSet)
}
}.searchable(text: $searchText) // 4
}
}
var searchResults: [Vehicle] { // 1
if searchText.isEmpty {
return vehicles
} else {
return vehicles.filter {$0.name.lowercased().contains(searchText.lowercased())}
}
}
Note that the ForEach now iterates over the searchResult, which contains all the vehicles if the searchText is empty, or the search results based on the vehicle’s name otherwise.
It is a very useful element!