SearchBar in SwiftUI

Rishabh Jain
3 min readMar 31, 2021

Introduction

Pre-requisite for SwiftUI development :-

  1. Xcode 11
  2. MacOS Catalina 10.15.2

Getting Started

SwiftUI does not have an activity indicator built in, so we need to use the UISearchBar which is part of UIKit.

Application Entry Point

Creating a New Project for Playing with SwiftUI. First, fire up Xcode and create a new Project. I created a project named DemoSearchBar.

Once you save the project, Xcode should load the ContentView.swift file and display a design/preview canvas.

By default, Xcode generates some SwiftUI code for ContentView.swift. However, the preview canvas doesn’t render the app preview. You have to click the Resume button in order to see the preview.

Creating theSearchBar

Here, We are using the default UISearchBar that comes with UIKit. To use this we need to create a new struct that conforms to UIViewRepresentable. Here we are implementing two of the methods from UIViewRepresentable which are, makeUIView and updateUIView.

The Coordinator does conform to the UISearchBarDelegate protocol, which is used to implement what happens when text is entered.

Till now, we created a simple search bar. Now, let’s make a List View having multiple rows and after that will filter the data using searchBar and its delegate.

The filter in the ForEach changes to only compare lowercased strings.

List {ForEach(self.nameAaray.filter {self.text.isEmpty ? true : $0.lowercased().contains(self.text.lowercased())}, id: \.self) { name inText(name)
}}

Conclusion

I hope you enjoyed reading this. In this tutorial, we got an introduction about the UISearchBar control of SwiftUI.

Please find the Github link.
Github:- https://github.com/imrishuj/SU-UISearchBar

Thanks for reading and good luck with your next SwiftUI Tutorial!

--

--