NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to add a search bar to filter your data

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Updated in iOS 16

SwiftUI’s searchable() modifier lets us place a search bar directly into a NavigationStack, which will either stay fixed for simple layouts or automatically appear and scroll when used with a list. For more power, you can also use searchScopes() to control where the search takes place.

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

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

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

Download this as an Xcode project

Tip: By attaching searchable() to NavigationStack or NavigationSplitView, we’re leaving it to the system to decide where is most appropriate to display the search box. If you specifically want it attached to one view, you can move it as needed, or try its placement parameter.

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 {
        NavigationStack {
            Text("Searching for \(searchText)")
                .navigationTitle("Searchable Example")
        }
        .searchable(text: $searchText, prompt: "Look for something")            
    }
}

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 {
        NavigationStack {
            List {
                ForEach(searchResults, id: \.self) { name in
                    NavigationLink {
                        Text(name)
                    } label: {
                        Text(name)
                    }
                }
            }
            .navigationTitle("Contacts")
        }
        .searchable(text: $searchText)            
    }

    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 {
        NavigationStack {
            List {
                ForEach(searchResults, id: \.self) { name in
                    NavigationLink {
                        Text(name)
                    } label: {
                        Text(name)
                    }
                }
            }
            .navigationTitle("Contacts")
        }
        .searchable(text: $searchText) {
            ForEach(searchResults, id: \.self) { result in
                Text("Are you looking for \(result)?").searchCompletion(result)
            }
        }
    }

    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.

For more advanced searches, you can add scopes to your search box to let the user select what kind of search they want by adding the searchScopes() modifier. This needs to be bound to some state that tracks the currently active search scope, and you can then provide scopes using a trailing closure.

As an example, we could write some code to let the user choose between searching all their inbox or just their favorite messages, like this:

struct Message: Identifiable, Codable {
    let id: Int
    var user: String
    var text: String
}

enum SearchScope: String, CaseIterable {
    case inbox, favorites
}

struct ContentView: View {
    @State private var messages = [Message]()

    @State private var searchText = ""
    @State private var searchScope = SearchScope.inbox

    var body: some View {
        NavigationStack {
            List {
                ForEach(filteredMessages) { message in
                    VStack(alignment: .leading) {
                        Text(message.user)
                            .font(.headline)

                        Text(message.text)
                    }
                }
            }
            .navigationTitle("Messages")
        }
        .searchable(text: $searchText)
        .searchScopes($searchScope) {
            ForEach(SearchScope.allCases, id: \.self) { scope in
                Text(scope.rawValue.capitalized)
            }
        }
        .onAppear(perform: runSearch)
        .onSubmit(of: .search, runSearch)
        .onChange(of: searchScope) { _ in runSearch() }
    }

    var filteredMessages: [Message] {
        if searchText.isEmpty {
            return messages
        } else {
            return messages.filter { $0.text.localizedCaseInsensitiveContains(searchText) }
        }
    }

    func runSearch() {
        Task {
            guard let url = URL(string: "https://hws.dev/\(searchScope.rawValue).json") else { return }

            let (data, _) = try await URLSession.shared.data(from: url)
            messages = try JSONDecoder().decode([Message].self, from: data)
        }
    }
}

Download this as an Xcode project

Tip: If you add more scopes than there is space for, your scope titles will be truncated.

Hacking with Swift is sponsored by Stream

SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.

Try now!

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.