How to add Search in UITableView using Swift

How to add Search in UITableView using Swift

Today, I’m going to show you how to search for items in a UITableView using the UISearchBar.

In this example, we have a UITableView already set up, and the only thing we do is to add the searching functionality.

We have a list of countries as sample data and using the search bar we get the country we want faster.

Adding Search Bar on TableView

Add the UISearchBar at the top of your UITableView.

… and give the name searchBar.

In the ViewController add a Boolean called searching to know when to switch between the full list of items and the list of items from the searching results.

Also add two arrays, countryList and searchedCountry, for all items and the items from the searched results, respectively.

In the numberOfRowsInSection function, when searching is true, then will return the number of the items from the search results, and when is not, will return all items.

In cellForRowAt function, will do the same thing, but this time will return the country’s name for each row.

… and also the same when you select a cell using the didSelectRowAt function.

Create an extension for UISearchBarDelegate.

In searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) function, which is called every time we typing, pass the results to the searchedCountry array after using filter to detect if the text we typing in the search bar matches an item in the list.

… and when we press the Cancel button:

Customizing the Search Bar

Change the color of the glass icon:

Change the color of the text field inside the search bar:

Hide or show the Cancel button on the right side of search bar:

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

avatar
  Subscribe  
Notify of

Follow me

Newsletter

Subcribe for weekly emails! Get my posts of the week right in your inbox!