< Creating a secondary view for NavigationView | Changing a view’s layout in response to size classes > |
Before our List
view 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 navigationTitle()
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 localizedCaseInsensitiveContains()
to filter the array based on their search criteria:
var filteredResorts: [Resort] {
if searchText.isEmpty {
return resorts
} else {
return resorts.filter { $0.name.localizedCaseInsensitiveContains(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 AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.