Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook A guide to solving the most common problems and learning best practices while building SwiftUI apps

Arrow left icon
Product type Paperback
Published in Nov 2021
Publisher Packt
ISBN-13 9781803234458
Length 616 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Edgar Nzokwe Edgar Nzokwe
Author Profile Icon Edgar Nzokwe
Edgar Nzokwe
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Chapter 1: Using the Basic SwiftUI Views and Controls 2. Chapter 2: Going Beyond the Single Component with Lists and Scroll Views FREE CHAPTER 3. Chapter 3: Exploring Advanced Components 4. Chapter 4: Viewing while Building with SwiftUI Preview 5. Chapter 5: Creating New Components and Grouping Views with Container Views 6. Chapter 6: Presenting Extra Information to the User 7. Chapter 7: Drawing with SwiftUI 8. Chapter 8: Animating with SwiftUI 9. Chapter 9: Driving SwiftUI with Data 10. Chapter 10: Driving SwiftUI with Combine 11. Chapter 11: SwiftUI Concurrency with async await 12. Chapter 12: Handling Authentication and Firebase with SwiftUI 13. Chapter 13: Handling Core Data in SwiftUI 14. Chapter 14: Creating Cross-Platform Apps with SwiftUI 15. Chapter 15: SwiftUI Tips and Tricks 16. Other Books You May Enjoy

Using Searchable lists

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.

Getting ready

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:

  1. From the navigation pane, select the project's name (SearchableLists).
  2. Select Build settings.
  3. Under Deployment, select iOS Deployment Target.
  4. Select iOS 15.0 from the popup menu.

These steps are shown in the following screenshot:

Figure 2.11 – Setting the iOS Deployment Target

Figure 2.11 – Setting the iOS Deployment Target

How to do it…

Let's create an app to search through possible messages between a parent and their child. The steps are as follows:

  1. Before the 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.....", 
            ]
  2. Add a 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")
            }
        }
  3. Below the 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

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.

How it works…

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.

There's more…

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.

You have been reading a chapter from
SwiftUI Cookbook - Second Edition
Published in: Nov 2021
Publisher: Packt
ISBN-13: 9781803234458
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime