0
0
iOS Swiftmobile~5 mins

Search with searchable modifier in iOS Swift

Choose your learning style9 modes available
Introduction

Adding a search bar helps users quickly find items in a list. The searchable modifier makes it easy to add this feature in SwiftUI.

You have a list of contacts and want users to find a name fast.
Your app shows a list of products and users want to search by keyword.
You display a list of messages and want to filter them by text.
You want to add a search bar to any scrollable content without extra setup.
Syntax
iOS Swift
List(items, id: \.self) { item in
    Text(item)
}
.searchable(text: $searchText, prompt: "Search items")

The searchable modifier is added to a view like List or ScrollView.

You bind a @State string variable to text to track the search input.

Examples
Basic searchable list with default prompt.
iOS Swift
@State private var searchText = ""

List(fruits, id: \.self) { fruit in
    Text(fruit)
}
.searchable(text: $searchText)
Search bar with a custom prompt message.
iOS Swift
@State private var searchText = ""

List(countries, id: \.self) { country in
    Text(country)
}
.searchable(text: $searchText, prompt: "Find a country")
Searchable modifier on a ScrollView with manual filtering.
iOS Swift
@State private var searchText = ""

ScrollView {
    VStack {
        ForEach(items.filter { searchText.isEmpty || $0.localizedCaseInsensitiveContains(searchText) }, id: \.self) { item in
            Text(item)
        }
    }
}
.searchable(text: $searchText)
Sample App

This app shows a list of fruits with a search bar on top. Typing in the search bar filters the list in real time.

iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var searchText = ""
    let fruits = ["Apple", "Banana", "Cherry", "Date", "Fig", "Grape"]

    var filteredFruits: [String] {
        if searchText.isEmpty {
            return fruits
        } else {
            return fruits.filter { $0.localizedCaseInsensitiveContains(searchText) }
        }
    }

    var body: some View {
        NavigationView {
            List(filteredFruits, id: \.self) { fruit in
                Text(fruit)
            }
            .navigationTitle("Fruits")
            .searchable(text: $searchText, prompt: "Search fruits")
        }
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

The searchable modifier works on iOS 15 and later.

Filtering the list based on the search text is done manually in your code.

Use localizedCaseInsensitiveContains for case-insensitive search.

Summary

The searchable modifier adds a search bar to lists or scroll views.

Bind a @State string to track user input.

Filter your data based on the search text to update the displayed list.