How to: Add a search bar to NavigationView in SwiftUI
A fast way to add a search bar to your SwiftUI app with fuzzy search and NavigationView. (Bonus: becomeFirstResponder)
In the latest version of iOS 15 sdk, you can now use the
.searchable(:)modifier to achieve search behavior. Only continue with this article if you need to support iOS 13 and higher!
This year, at the top of the WWDC wish list, is for the SwiftUI team to add a search bar to the framework. There are so many ways to add search today from using a
TextField view to tapping into UIKit and using
UISearchBar via UIViewRepresentable.
Nevertheless, it’s a hassle, but I’m going to show you how you can add it relatively fast using SwiftUIX. SwiftUIX is a library full of various views missing in the SwiftUI standard library, one of being a search bar. They’ve conveniently added a modifier to
NavigationView that allows you to add a search bar and customize it with a few modifiers.
Under the hood it’s using view representable meaning it taps into UIKit like I mention above.
To install SwiftUIX, add the package to your project via SPM. The library doesn't support cococapods, but nothing stops you from forking it and adding your own podspec and using it as a development pod.
Next, we have to import our new package and then call the search bar modifier on our view. For this example, I will create a
List in a
NavigationView with the code below.