
SwiftUI Cookbook
By :

List
views can hold from one to an uncountable number of items. As the number of items in a list increases, it is usually helpful to provide users with the ability to search through the list for a specific item without having to scroll through the whole list.
In this recipe, we'll introduce the .searchable()
modifier and discuss how it can be used to search through items in a list.
Create a new SwiftUI project and name it SearchableLists
.
The searchable modifier is only available in iOS 15+. In your build settings, make sure that your iOS Deployment Target is set to iOS 15. Use the following steps to change the deployment target:
These steps are shown in the following screenshot:
Figure 2.11 – Setting the iOS Deployment Target
Let's create an app to search through possible messages between a parent and their child. The steps are as follows:
ContentView
struct's body, add a State
variable to hold the search text and sample messages:@State private var searchText="" let messages = [ "Dad, can you lend me money?", "Nada. Does money grow on trees?", "What is money made out of?", "Paper", "Where does paper come from?", "Huh.....", ]
NavigationView
, a List
to display the search results, a navigationBarTitle
modifier, and a .searchable
modifier:var body: some View { NavigationView { List{ ForEach(searchResults, id: \.self){ msg in Text(msg) } } .searchable(text: $searchText) .navigationBarTitle("Order number") } }
body
variable, add the searchResults
computed property, which returns an array of elements representing the result of the search:var searchResults: [String] { if searchText.isEmpty { return messages }else{ return messages.filter{ $0.lowercased().contains (searchText.lowercased())} } }
Run the app in canvas mode. The resulting live preview should look as follows:
Figure 2.12 – Searchable List live preview
Now, type something within the search field and watch how the content is filtered to match the result of the search text that was entered.
The searchText
state variable holds the value that's being searched for and is passed as an argument to the .searchable
modifier. Each time the value of searchText
changes, the computed property, searchResults
, gets calculated. Finally, the value of searchResults
is used in the ForEach
struct to display a filtered list of items based on the search text.
You can provide autocomplete information by adding a closure to the .searchable
modifier, as shown here:
.searchable(text: $searchText){ ForEach(searchResults, id: \.self) { result in ' Text((result)).searchCompletion(result) } }
The autocomplete feature provides the user with possible suggestions that match the search string they've entered so far. Clicking on one of the suggestions auto-fills the rest of the search text area and displays the results from the search.