Creating a search bar for SwiftUI

Axel Hodler
3 min readJan 21, 2020

SwiftUI does not offer a SearchBar View out of the box yet. But we can fall back to using UISearchBar of UIKit.

We are going to build the following search functionality. A list of cars will be filtered by a search term

Recording of the iOS Simulator

Using to the view we want to change. In our case ContentView. We add an array of cars and the initial SwiftUI view structure.

The result in the preview or the simulator should look as follows

Simple list with a title

No search bar yet. Let’s continue creating our own SearchBar view. Making use of the existing UISearchBar , a view for receiving search information from the user.

The Coordinator does conform to the UISearchBarDelegate protocol, which is used to implement what happens when text is entered. In our case setting the text String in the view.

Now we can use the SearchBar in our ContentView. We change it to the following. Feel free to add some more cars.

The look will change into

We can enter text but there is no filtering happening yet. We can change that by using a filter in the ForEach

If the searchText is empty we display all cars. If not we check which cars contain the searchText. To avoid having every term we enter capitalised we change the makeUIView function in our SearchBar by using autocapitalizationType .none

We get

All the cars containing the String or are shown.

Searching for model won’t yield the Tesla Model 3 though.

Let’s improve our search to ignore capitalisation.

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

Thus we find what we are searching for

The functionality is done. We could stop. Although according to the Apple Human Interface Guidelines for iOS on search bars we should provide hints and context in the search bar.

A placeholder could help. We do that by adding

searchBar.placeholder = "Search"

before returning in makeUIView of the SearchBar

Or even better

searchBar.placeholder = "Search cars"

To avoid having the placeholder hard coded in SearchBar we could let SearchBar accept the placeholder as a parameter.

If everything would be put into one file the code should be

New Xcode project, replacing the existing ContentView with the above and we can play around.

The project repo is on Github

Thanks to Markus K and Kostas Tsole for all the iOS support :)

--

--

Axel Hodler

Building things. Usually by writing code. www.hodler.co. Software Engineering @porschedigital