import SwiftUI
struct FruitSearchView: View {
let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"]
@State private var searchText = ""
var filteredFruits: [String] {
if searchText.isEmpty {
return fruits
} else {
return fruits.filter { $0.localizedCaseInsensitiveContains(searchText) }
}
}
var body: some View {
NavigationView {
List(filteredFruits, id: \.self) { fruit in
Text(fruit)
}
.navigationTitle("Fruits")
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .automatic), prompt: "Search fruits")
}
}
}
struct FruitSearchView_Previews: PreviewProvider {
static var previews: some View {
FruitSearchView()
}
}We keep the full list of fruits in a constant array. The searchText state variable holds what the user types in the search bar. We create a computed property filteredFruits that returns all fruits if the search text is empty, or only those fruits that contain the search text ignoring case.
The List shows the filtered fruits. We add the .searchable modifier to the list with a binding to searchText. This automatically adds a search bar in the navigation bar area. As the user types, the list updates to show matching fruits.
This approach uses SwiftUI's built-in searchable modifier for a simple and clean search UI.