SwiftUI series 7: Building a Simple Fruit Search App in SwiftUI
In this tutorial, we'll create a simple yet effective fruit search application using SwiftUI. This app will demonstrate how to implement a search functionality with a list of fruits. Let's break down the code and understand each component.
Setting Up the Project
First, create a new SwiftUI project and add a new file called SearchView.swift
. This will be our main view containing the search functionality.
The Code Structure
import SwiftUI
struct SearchView: View {
@State private var searchText = ""
let names = ["Apple","Banana","Orange","Mango","Strawberry","Pineapple","Grape","Kiwi"]
// ... rest of the code
}
Key Components:
-
State Variable:
- We declare
searchText
as a@State
variable to store the user's search input@State private var searchText = ""
- We declare
-
Fruit Data:
- A simple array of fruit names
let names = ["Apple","Banana","Orange","Mango","Strawberry","Pineapple","Grape","Kiwi"]
- A simple array of fruit names
-
Search Filter Logic:
var filteredNames: [String] { if searchText.isEmpty { return names } else { return names.filter { $0.lowercased().contains(searchText.lowercased()) } } }
This computed property:
- Returns all names if search text is empty
- Filters names that contain the search text (case-insensitive)
-
User Interface:
var body: some View { NavigationStack { List(filteredNames, id: \.self) { name in Text(name) } .searchable(text: $searchText, placement: .automatic, prompt: "Search William Jiamin's Favorite Fruits ...") .navigationTitle("Search Fruits App") } }
Features Explained
-
NavigationStack:
- Provides navigation capabilities and proper layout structure
-
List View:
- Displays the filtered fruits in a scrollable list
- Uses
id: \.self
for unique identification of list items
-
Searchable Modifier:
- Adds a search bar to the view
- Binds to the
searchText
state variable - Includes a custom prompt message
How It Works
- When the app launches, it displays all fruits in the list
- As the user types in the search bar:
- The
searchText
state updates - The
filteredNames
computed property filters the list - The List view automatically updates with filtered results
- The
Conclusion
This simple yet functional implementation shows how easy it is to create a searchable list in SwiftUI. The code is concise and takes advantage of SwiftUI's declarative syntax and built-in search functionality.
Try adding more features like:
- Custom fruit cell designs
- Categories for fruits
- Favorite fruit marking functionality
Happy coding! 🍎🍌🍊