6.2. Setting up the View Controller: Handling the Search Bar
//
// 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) {
}
}Handling when the User is Typing on the Search Bar

Last updated