SwiftUI

How To Add A Search Bar To A List In SwiftUI

SwiftUI now has the ability to add a search bar in iOS 15. This is done through the searchable() modifier which adds a search bar under your navigation view automatically.

To get started, we need our data and a state property to keep track of the search term.

@State private var searchTerm = ""
private let cats = ["Persian", "Tabby", "Ragdoll", "Sphynx", "Maine Coon"]

Next, we need a computed property to filter our data depending on the search term. This is straightforward to do with a ternary operator and a filter.

var results: [String] {
  searchTerm.isEmpty ? cats : cats.filter { $0.contains(searchTerm) }
}

Finally we can display our results in the list. To add the search bar, just add the .searchable() modifier.

NavigationView
    List {
        ForEach(results, id: \.self) { catBreed in
            Text(catBreed)
        }
    }
    .searchable(text: $searchTerm)
    .navigationTitle("Cat Breeds")
}

Now if you build and run, a search bar should show underneath your navigation title where you can filter the list of your favourite cat breeds.


Thanks for reading!


Full Code

struct ContentView: View {

  @State private var searchTerm = ""
  private let cats = ["Persian", "Tabby", "Ragdoll", "Sphynx", "Maine Coon"]

  var results: [String] {
    searchTerm.isEmpty ? cats : cats.filter { $0.contains(searchTerm) }
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(results, id: \.self) { catBreed in
          Text(catBreed)
        }
      }
      .searchable(text: $searchTerm)
      .navigationTitle("Cat Breeds")
    }
  }
}