6.2. Setting up the View Controller: Handling the Search Bar

Let's open ViewController.swift file and put the following code there:

//
//  ViewController.swift
//  SearchBarDemo
//
//  Created by Sakib Miazi on 6/12/23.
//

import UIKit

class ViewController: UIViewController {
    
    let mainScreen = MainScreenView()
    
    //MARK: the list of names...
    var namesDatabase = [
        "Marvin Cook","Samira Jimenez","Coral Hancock","Xander Wade","Terence Mcneil",
        "Dewey Buckley","Ophelia Higgins","Asiya Anthony","Francesco Knight",
        "Claude Gonzalez","Demi Decker","Casey Park","Jon Hendrix","Hope Harvey",
        "Richie Alexander","Carmen Proctor","Mercedes Callahan","Yahya Gibbs",
        "Julian Pittman","Shauna Ray"
    ]
    
    //MARK: the array to display the table view...
    var namesForTableView = [String]()
    
    override func loadView() {
        view = mainScreen
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //MARK: sorting the names list...
        namesDatabase.sort()
        
        //MARK: setting up Table View data source and delegate...
        mainScreen.tableViewSearchResults.delegate = self
        mainScreen.tableViewSearchResults.dataSource = self
        
        //MARK: setting up Search Bar delegate...
        mainScreen.searchBar.delegate = self
        
        //MARK: initializing the array for the table view with all the names...
        namesForTableView = namesDatabase
    }
}

//MARK: adopting Table View protocols...
extension ViewController: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return namesForTableView.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: Configs.searchTableViewID, for: indexPath) as! SearchTableViewCell
        
        cell.labelTitle.text = namesForTableView[indexPath.row]
        return cell
    }
    
}

//MARK: adopting the search bar protocol...
extension ViewController: UISearchBarDelegate{
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
    }
}

In the above code:

  • On lines 15 through 21, we create the list of names namesDatabase, which will be used as the data source for the names.

  • On line 24, we define an array namesForTableView that we will use to display the TableView.

  • On lines 30 through 46, we write the code for viewDidLoad.

    • On lines 37 through 38, we set the delegate and data source of the table view.

    • On line 41, we set the search bar's delegate to self.

    • On line 44, we initialize the array for table view with all the names.

  • On lines 48 through 62, we adopt the protocols related to the table view delegate and data source as we have been doing so far.

  • On lines 65 through 69, we adopt the protocol UISearchBarDelegate regarding the search bar's delegate.

    • We have to override the searchBar() method regarding textDidChange if we want to handle the search bar behaviors while the user is typing on the search bar.

    • On line 66, the method regarding textDidChange gets called when the search bar senses that something is typed on it.

Let's put the following code into the method regarding textDidChange (in between lines 66 and 68 in the above code):

In the above code:

  • ,On line 4, we are checking if the user removed the search text. If the searchText is empty, then we load all the names.

  • Else, on lines 6 through 14,

    • The user typed something on the search bar.

    • So first, we remove all the names from the array on line 7.

    • Then we search all the names to find if the searchText matches any part of any name we have (lines 9 through 13). We append the matched names in the array for the table view.

    • Then on line 15, we reload the table view data to display the search result.

Let's run the app again:

Yay! Our simple search bar is working!

Last updated

Was this helpful?