[:en]Swift search feature:
It’s easy to search any data among a vast amount of data by using swfit search feature:
//
// ViewController.swift
// search
//
// Created by Cambridge on 7/4/2019.
// Copyright © 2019 Cambridge . All rights reserved.
//
import UIKit
// Search Step 2
class ViewController: UITableViewController, UISearchResultsUpdating {
let searchController = UISearchController(searchResultsController: nil)
var alldata = ["fish", "tree", "monkey", "three", "see", "sea"]
var filteredData = [String]()
var inSearchMode = false
override func viewDidLoad() {
super.viewDidLoad()
// Search Step 3
filteredData = alldata
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
// Search Step 4
func updateSearchResults(for searchController: UISearchController) {
// If we haven't typed anything into the search bar then do not filter the results
if searchController.searchBar.text! == "" {
filteredData = alldata
} else {
// Filter the results
filteredData = alldata.filter { $0.lowercased().contains(searchController.searchBar.text!.lowercased()) }
}
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "cell")
cell.textLabel?.text = self.filteredData[indexPath.row]
cell.detailTextLabel?.text = self.filteredData[indexPath.row] // subtitle of tableview
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row +++++ \(indexPath.row) selected")
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
if let cellselected : String = currentCell.textLabel!.text{
print("cell selected:\(cellselected)")
}
}
}
[:]
