< Using groups as transparent layout containers | Sharing @Observable objects through SwiftUI's environment > |
iOS can add a search bar to our views using the searchable()
modifier, and we can bind a string property to it to filter our data as the user types.
To see how this works, try this simple example:
struct ContentView: View {
@State private var searchText = ""
var body: some View {
NavigationStack {
Text("Searching for \(searchText)")
.searchable(text: $searchText, prompt: "Look for something")
.navigationTitle("Searching")
}
}
}
Important: You need to make sure your view is inside a NavigationStack
, otherwise iOS won’t have anywhere to put the search box.
When you run that code example, you should see a search bar you can type into, and whatever you type will be shown in the view below.
In practice, searchable()
is best used with some kind of data filtering. Remember, SwiftUI will reinvoke your body property when an @State
property changes, so you could use a computed property to handle the actual filtering:
struct ContentView: View {
@State private var searchText = ""
let allNames = ["Subh", "Vina", "Melvin", "Stefanie"]
var filteredNames: [String] {
if searchText.isEmpty {
allNames
} else {
allNames.filter { $0.localizedStandardContains(searchText) }
}
}
var body: some View {
NavigationStack {
List(filteredNames, id: \.self) { name in
Text(name)
}
.searchable(text: $searchText, prompt: "Look for something")
.navigationTitle("Searching")
}
}
}
When you run that, iOS might automatically hide the search bar at the very top of the list – you’ll need to pull down gently to reveal it, which matches the way other iOS apps work. iOS doesn’t require that we make our lists searchable, but it really makes a huge difference to users!
Tip: localizedStandardContains()
is the best way to search for things based on user input, because it automatically ignores case and accents such as the é in café.
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.