FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to add a search bar to filter your data

Paul Hudson    @twostraws   

Updated for Xcode 13.0

New in iOS 15

SwiftUI’s searchable() modifier lets us place a search bar directly into a NavigationView, which will either stay fixed for simple layouts or automatically appear and scroll when used with a list.

In its simplest form, this is just a matter of adding searchable() to some view inside a navigation view, like this:

struct ContentView: View {
    @State private var searchText = ""

    var body: some View {
        NavigationView {
            Text("Searching for \(searchText)")
                .searchable(text: $searchText)
                .navigationTitle("Searchable Example")
        }
    }
}

Download this as an Xcode project

You can also provide a string to display as a prompt for the search box, like this:

struct ContentView: View {
    @State private var searchText = ""

    var body: some View {
        NavigationView {
            Text("Searching for \(searchText)")
                .searchable(text: $searchText, prompt: "Look for something")
                .navigationTitle("Searchable Example")
        }
    }
}

Download this as an Xcode project

In practice, though, you’re more likely to use it to filter a List of data, something like this:

struct ContentView: View {
    let names = ["Holly", "Josh", "Rhonda", "Ted"]
    @State private var searchText = ""

    var body: some View {
        NavigationView {
            List {
                ForEach(searchResults, id: \.self) { name in
                    NavigationLink(destination: Text(name)) {
                        Text(name)
                    }
                }
            }
            .searchable(text: $searchText)
            .navigationTitle("Contacts")
        }
    }

    var searchResults: [String] {
        if searchText.isEmpty {
            return names
        } else {
            return names.filter { $0.contains(searchText) }
        }
    }
}

Download this as an Xcode project

As the search bar now appears inside a list, it will usually start life hidden – users need to tug the list gently downwards at the top to reveal it.

For more advanced uses, searchable() allows us to show a list of suggestions to our users, even adding extra completion information to save them typing so much. This is done by passing a function to searchable() that returns a view containing your suggestions, and if you want users to be able to tap to complete their search use the searchCompletion() modifier for each suggestion.

So, we could modify our previous example to provide tappable suggestions as the user types, rather than just filtering the whole list in-place:

struct ContentView: View {
    let names = ["Holly", "Josh", "Rhonda", "Ted"]
    @State private var searchText = ""

    var body: some View {
        NavigationView {
            List {
                ForEach(searchResults, id: \.self) { name in
                    NavigationLink(destination: Text(name)) {
                        Text(name)
                    }
                }
            }
            .searchable(text: $searchText) {
                ForEach(searchResults, id: \.self) { result in
                    Text("Are you looking for \(result)?").searchCompletion(result)
                }
            }
            .navigationTitle("Contacts")
        }
    }

    var searchResults: [String] {
        if searchText.isEmpty {
            return names
        } else {
            return names.filter { $0.contains(searchText) }
        }
    }
}

Download this as an Xcode project

That uses “Are you looking for Holly?” and similar for each suggestion, so you can see how it looks on screen. It also uses each person’s name as the completion, meaning that if you type “Ho” and tap “Holly” the search bar will autocomplete with the full name.

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.4/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.