Book Image

SwiftUI Cookbook - Second Edition

By : Giordano Scalzo, Edgar Nzokwe
Book Image

SwiftUI Cookbook - Second Edition

By: Giordano Scalzo, Edgar Nzokwe

Overview of this book

SwiftUI provides an innovative and simple way to build beautiful user interfaces (UIs) for all Apple platforms, from iOS and macOS through to watchOS and tvOS, using the Swift programming language. In this recipe-based cookbook, you’ll cover the foundations of SwiftUI as well as the new SwiftUI 3 features introduced in iOS 15 and explore a range of essential techniques and concepts that will help you through the development process. The cookbook begins by explaining how to use basic SwiftUI components. Once you’ve learned the core concepts of UI development, such as Views, Controls, Lists, and ScrollViews, using practical implementations in Swift, you'll advance to adding useful features to SwiftUI using drawings, built-in shapes, animations, and transitions. You’ll understand how to integrate SwiftUI with exciting new components in the Apple development ecosystem, such as Combine for managing events and Core Data for managing app data. Finally, you’ll write iOS, macOS, and watchOS apps by sharing the same SwiftUI codebase. By the end of this SwiftUI book, you'll have discovered a range of simple, direct solutions to common problems encountered when building SwiftUI apps.
Table of Contents (17 chapters)

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.