Skip to content

Instantly share code, notes, and snippets.

@vmax
Last active March 1, 2017 20:19
Show Gist options
  • Save vmax/05449faefa913b63811cd8ae1492ddf5 to your computer and use it in GitHub Desktop.
Save vmax/05449faefa913b63811cd8ae1492ddf5 to your computer and use it in GitHub Desktop.
Easy way to make data in UITableView searchable
class DataViewController: UITableViewController, UISearchResultsUpdating {
var data = [Data]()
var filteredData = [Data]()
@available(iOS 8.0, *)
public func updateSearchResults(for searchController: UISearchController) {
let query = searchController.searchBar.text!
filteredData = data.filter { element in
element.lowercased().contains(query.lowercased())
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let current: Data
if searchController.isActive && searchController.searchBar.text != "" {
current = filteredData[indexPath.row]
} else {
current = data[indexPath.row]
}
// …
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return filteredData.count
}
return data.count
}
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment