Search Bar in SwiftUI

Ahmed Adam
3 min readJun 29, 2023

--

Creating Search Bar in SwiftUI.

The desired outcome.

In modern mobile applications, search functionality plays a crucial role in helping users find relevant content quickly. SwiftUI, Apple's declarative UI framework, offers a straightforward and elegant way to incorporate a search bar into your app. In this article, we'll explore how simple it is to achieve this with SwiftUI and create a seamless search experience for your users.

Introduction

In this article, we will explore how to implement a searchable followers list using SwiftUI. We’ll leverage SwiftUI’s built-in searchable modifier to create a dynamic search functionality in our app. Let's dive into the code and see how it all comes together.

Prerequisites

Before proceeding, ensure you have a basic understanding of SwiftUI and its core concepts. Familiarity with JSON decoding using Codable and fetching data asynchronously with async/await will also be beneficial.

struct Follower: Codable {
var id: Int
var avatarUrl: String
var login: String
}

struct ContentView: View {
@State private var followers: [Follower] = []
@State private var searchTerm = ""

var filteredFollowers: [Follower] {
guard !searchTerm.isEmpty else {return followers}
return followers.filter{$0.login.localizedCaseInsensitiveContains(searchTerm)}
}

var body: some View {
NavigationStack{
List(filteredFollowers, id: \.id) { follower in
HStack(spacing: 20) {
AsyncImage(url: URL(string: follower.avatarUrl)) { image in
image
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(Circle())
} placeholder: {
Circle()
.foregroundColor(.secondary)
}
.frame(width: 44, height: 44)

Text(follower.login)
.font(.title3)
.fontWeight(.medium)
}
}
.navigationTitle("Followers")
.task { followers = await getGithubFollower() }
.searchable(text: $searchTerm, prompt: "Search Followers")
}
}

func getGithubFollower() async -> [Follower] {
let url = URL(string: URLStr)!
let (data, _) = try! await URLSession.shared.data(from: url)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try! decoder.decode([Follower].self, from: data)
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

The Code:

The provided code demonstrates the implementation of a searchable followers list. Let’s break it down and understand how it works.

  • @State Variables:
    - followers -> stores an array of Follower objects.
    - searchTerm -> holds the search text entered by the user.
  • filteredFollowers Computed Property:
    - Returns the filtered list of followers based on the search term.
    - Uses the filter method to compare the login property of each follower against the search term, disregarding case sensitivity.
  • View Body:
    - List -> Displays the filtered followers.
    - Each follower is represented by -> a HStack containing an async image and their login name.
    - NavigationStack -> Wraps the list and adds navigation-related functionality.
    - navigationTitle -> Sets the title of the navigation bar to “Followers”.
  • task:
    - Asynchronously fetches the follower data from the GitHub API using the getGithubFollower function.
    - searchable -> Enables the search functionality.
    - Binds the searchTerm to the search bar’s text field and provides a prompt text.
  • getGithubFollower Function:
    - Uses async/await to fetch follower data from the GitHub API.
    - Sends a request to the specified URL.
    - Decodes the received JSON data into an array of Follower objects using JSONDecoder.

Conclusion:

In this article, we explored how to implement a searchable followers list in SwiftUI. By leveraging the searchable modifier, we created a dynamic search experience for users to find specific followers. SwiftUI's declarative syntax and built-in functionality allow us to achieve this with ease.

Feel free to customize the code according to your requirements. You can modify the UI, adjust the API endpoint, or enhance the search logic to suit your app’s needs. SwiftUI’s flexibility empowers developers to create intuitive and powerful interfaces while maintaining simplicity in their implementations.

--

--

Ahmed Adam
Ahmed Adam

Written by Ahmed Adam

Senior iOS Engineer | Swift | SwiftUI | Objective-C | Agile | Scrum | Mobile Development |

No responses yet