Chapter 37
Implementing Search Bar Using Searchable

When SwiftUI was first released, the framework didn't come with a built-in modifier for handling search in List views. Developers had to create their own solutions. In earlier chapters, I showed you how to implement a search bar in SwiftUI using TextField and display search results. Since the release of iOS 15, the SwiftUI framework introduced a new modifier named searchable for List views.

In this chapter, we will look into this modifier and see easily it is to implement search for a list.

Basic Usage of Searchable

To demonstrate the usage of Searchable, please download the demo project from https://www.appcoda.com/resources/swiftui7/SwiftUISearchableStarter.zip.

Figure 1. The starter project
Figure 1. The starter project

The starter project already includes a list view that displays a set of articles. What I want to do is provide an enhancement by adding a search bar for filtering the articles. To add a search bar to the list view, all you need to do is declare a state variable (e.g., searchText) to hold the search text and attach a searchable modifier to the NavigationStack, like this:

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""