Chapter 24
Creating a Search Bar View and Working with Custom Binding
In a previous chapter, we demonstrated how to implement a search bar by reusing the UISearchBar component from the old UIKit framework. But have you ever considered building a search bar from scratch? Upon closer inspection, you'll find that it's not too difficult to implement. So, let's embark on building a SwiftUI version of a search bar in this chapter.
Not only will you learn how to create the search bar view, but we will also delve into the realm of custom bindings. We've touched upon bindings before, but we haven't shown you how to create a custom binding. Custom bindings are particularly useful when you need to incorporate additional program logic during read and write operations. Furthermore, we will explore how to dismiss the software keyboard in SwiftUI.
Figure 1 showcases the search bar we're about to build. It will have the same look and feel as the UISearchBar in UIKit. Additionally, we will implement a Cancel button, which will only appear when the user begins typing in the search field.

Implementing the Search Bar UI
We will now convert the previous project from using UISearchBar to our custom implementation of a search bar. To get started, please download the starter project from https://www.appcoda.com/resources/swiftui7/SwiftUIToDoListUISearchBar.zip. Once downloaded, compile the project to ensure it functions properly. The app should display a search bar; however, this bar is currently implemented using UIKit. Our goal is to convert it into a search bar view built entirely using SwiftUI.
Open the SearchBar.swift file, which is the file we will be focusing on. We will rewrite the entire code while keeping the struct name intact. We will still refer to it as SearchBar, which will still accept a binding of search text as an argument. From the perspective of the caller (i.e., ContentView), there is no need to make any changes. The usage will remain the same, as follows:
To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.