[:en]Swift search feature:
It’s easy to search any data among a vast amount of data by using swfit search feature:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
// // 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)") } } } |
[:]