How do I implement search and filtering in UIKit with Swift?

In this tutorial, we will explore how to implement search and filtering in UIKit using Swift. We will create a simple user interface that allows users to search through a list of items and filter the results dynamically.

Example Implementation

import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { let items = ["Apple", "Banana", "Cherry", "Date", "Fig", "Grape", "Honeydew"] var filteredItems: [String] = [] var isSearching = false let tableView = UITableView() let searchBar = UISearchBar() override func viewDidLoad() { super.viewDidLoad() setupSearchBar() setupTableView() } func setupSearchBar() { searchBar.delegate = self searchBar.placeholder = "Search fruits" navigationItem.titleView = searchBar } func setupTableView() { tableView.dataSource = self tableView.delegate = self tableView.frame = view.bounds view.addSubview(tableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return isSearching ? filteredItems.count : items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell") cell.textLabel?.text = isSearching ? filteredItems[indexPath.row] : items[indexPath.row] return cell } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { isSearching = false filteredItems.removeAll() } else { isSearching = true filteredItems = items.filter { $0.lowercased().contains(searchText.lowercased()) } } tableView.reloadData() } }

Swift UIKit Search Filtering iOS Development