In UIKit, you can add a search bar to a table view by setting the tableHeaderView
property of the table view to a UISearchBar
instance. In SwiftUI, you can achieve the same effect by using the searchable
modifier on a List
view. The searchable
modifier adds a search bar to the list and allows you to filter the list items based on the search text.
Here’s an example of how to add a search bar to a SwiftUI list, and filter the list items based on the search text:
import SwiftUI
struct ListView: View {
@State private var searchText = ""
var body: some View {
NavigationView {
List {
ForEach(filteredData(), id: \.self) { data in
Text(data)
}
}
.searchable(text: $searchText, prompt: "Search for item…")
.navigationTitle("Searchable List")
}
}
func filteredData() -> [String] {
let dataSource = ["apples", "bananas", "strawberries"]
if searchText.isEmpty {
return dataSource
}
return dataSource.filter({ $0.lowercased().contains(searchText.lowercased()) })
}
}
#Preview {
ListView()
}