create a searchviewcontroller in swift

To create a UISearchController that will allow users to search through a collection of data in an iOS app, follow these steps:

  1. Create a UISearchController object and set it as the navigationItem.searchController property of your view controller. You'll also need to set the definesPresentationContext property of your view controller to true so that the search controller doesn't obscure other UI elements.
main.swift
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
navigationItem.searchController = searchController
definesPresentationContext = true
202 chars
5 lines
  1. Set up a searchBar property on your view controller that will be used as the interface for the user to enter search terms.
main.swift
let searchBar = searchController.searchBar
searchBar.placeholder = "Enter search term"
searchBar.tintColor = .white // optional: set the color of the cancel button
164 chars
4 lines
  1. Implement the UISearchResultsUpdating protocol on your view controller to update the search results based on the user's input. Here's an example implementation that filters an array of strings:
main.swift
class MyViewController: UIViewController, UISearchResultsUpdating {

    var data = ["apple", "banana", "cherry", "date", "elderberry"]
    var filteredData = [String]()

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text?.lowercased() {
            filteredData = data.filter { $0.lowercased().contains(searchText) }
            tableView.reloadData()
        }
    }
}
453 chars
13 lines
  1. If you have a table view or collection view that displays the data being searched, you'll need to update its data source and reload its contents when the search results are updated:
main.swift
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return searchController.isActive ? filteredData.count : data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let text = searchController.isActive ? filteredData[indexPath.row] : data[indexPath.row]
    cell.textLabel?.text = text
    return cell
}
485 chars
11 lines

gistlibby LogSnag