Before the list in ContentView
is done, we’re going to add a SwiftUI modifier that makes our user’s experience a whole lot better without too much work: searchable()
. Adding this will allow users to filter the list of resorts we’re showing, making it easy to find the exact thing they’re looking for.
This takes only four steps, starting with a new @State
property in ContentView
to store the text the user is searching for:
@State private var searchText = ""
Second, we can bind that to our List
in ContentView
by adding this directly below the existing navigationDestination()
modifier:
.searchable(text: $searchText, prompt: "Search for a resort")
Third, we need a computed property that will handle the filtering of our data. If our new searchText
property is empty then we can just send back all the resorts we loaded, otherwise we’ll use localizedStandardContains()
to filter the array based on their search criteria:
var filteredResorts: [Resort] {
if searchText.isEmpty {
resorts
} else {
resorts.filter { $0.name.localizedStandardContains(searchText) }
}
}
And the final step is to use filteredResorts
as the data source for our list, like this:
List(filteredResorts) { resort in
And with that we’re done! If you run the app again you’ll see you can drag the resort list gently down to see the search box, and entering something in there will filter the list straight away. Honestly, searchable()
is one of the biggest “bang for buck” features in SwiftUI – it’s such an important feature for users, and took us only a few minutes to implement!
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.