Swift – Filter Bar Tutorial
In our previous tutorial we implemented a search bar for a table with information about cupcakes. In this tutorial we will extend the app to include a filter bar as below. You can download the starting source code for this tutorial here.
First of all add UISearchBarDelegate to our view controller
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate {
Then in view did load ad the following code. It will setup our filter bar and set the values for it which is All, Small, Medium and finally Large.
searchController.searchBar.scopeButtonTitles = ["All", "Small", "Medium", "Large"] searchController.searchBar.delegate = self
The we need to add the following new function which is going to apply the search for both the search box text and the filter bar selection:
func applySearch(searchText: String, scope: String = "All") { // If we haven't typed anything into the search bar then do not filter the results if searchController.searchBar.text! == "" { filteredCakes = cakes.filter { cake in let cakeSize = (scope == "All") || (cake.size == scope) return cakeSize } } else { // Filter the results based on the selected filer and search text filteredCakes = cakes.filter { cake in let cakeSize = (scope == "All") || (cake.size == scope) return cakeSize && cake.name.lowercased().contains(searchText.lowercased()) } } self.tableView.reloadData() }
It first checks if the search bar is empty, if so it will only apply the selected cupcake size in the filter bar. Otherwise it will only show cakes based on the search bar and the filter bar size.
Next modify the updateSearchResults function as below, and also add the searchBar selectedScopeButtonIndexDidChange function. These are called whenever you type text in the search bar or select a cupcake size from the filter bar.
func updateSearchResults(for searchController: UISearchController) { //applySearch(searchText: searchController.searchBar.text!) let searchBar = searchController.searchBar let selectedScope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] applySearch(searchText: searchController.searchBar.text!,scope: selectedScope) } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { applySearch(searchText: searchController.searchBar.text!,scope: searchBar.scopeButtonTitles![selectedScope]) }
Now you can run the app and see the filter bar working. You can either
- Select a cupcake size from the filter bar
- Type in the cake name you wish to search for
- Or use a combination of both
Good work! Have this E-Cupcake as a reward!