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.
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()
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?