Component - Search with searchable modifier
This SwiftUI component shows a list of items with a search bar on top. The searchable modifier adds a search field that filters the list as you type, making it easy to find items quickly.
This SwiftUI component shows a list of items with a search bar on top. The searchable modifier adds a search field that filters the list as you type, making it easy to find items quickly.
NavigationView
└── List
└── ForEach
└── Textsearchable modifier do in a SwiftUI view?searchablesearchable modifier adds a search bar UI element to a list or scroll view.searchText?text: $variable.$searchText passes the binding, so the correct syntax is .searchable(text: $searchText).struct ContentView: View {
@State private var searchText = ""
let fruits = ["Apple", "Banana", "Grape", "Apricot"]
var filteredFruits: [String] {
if searchText.isEmpty { return fruits }
return fruits.filter { $0.lowercased().contains(searchText.lowercased()) }
}
var body: some View {
List(filteredFruits, id: \.self) { fruit in
Text(fruit)
}
.searchable(text: $searchText)
}
}struct ContentView: View {
@State var searchText = ""
let items = ["One", "Two", "Three"]
var filteredItems: [String] {
items.filter { $0.contains(searchText) }
}
var body: some View {
List(filteredItems, id: \.self) { item in
Text(item)
}
.searchable(text: searchText)
}
}text: $searchText, not text: searchText.struct Contact: Identifiable {
let id = UUID()
let firstName: String
let lastName: String
}
struct ContentView: View {
@State private var searchText = ""
let contacts = [Contact(firstName: "John", lastName: "Doe"), Contact(firstName: "Jane", lastName: "Smith"), Contact(firstName: "Alice", lastName: "Johnson")]
var filteredContacts: [Contact] {
if searchText.isEmpty { return contacts }
return contacts.filter { contact in
contact.firstName.lowercased().contains(searchText.lowercased()) || contact.lastName.lowercased().contains(searchText.lowercased())
}
}
var body: some View {
List(filteredContacts) { contact in
Text("\(contact.firstName) \(contact.lastName)")
}
.searchable(text: $searchText)
}
}$searchText, so typing updates the filteredContacts list dynamically.Pass the test and this pattern moves unknown