Skip to content

Instantly share code, notes, and snippets.

@post799
Created May 26, 2019 19:01
Show Gist options
  • Save post799/2700357f3499195a39c7f9569060a057 to your computer and use it in GitHub Desktop.
Save post799/2700357f3499195a39c7f9569060a057 to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// SearchTableView
//
// Created by Andriy Aleksyeyev on 5/26/19.
// Copyright © 2019 Andriy Aleksyeyev. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate ,UITableViewDataSource, UISearchResultsUpdating {
let myInfo = ["San Diego","Los Angeles","New-York","Paris"]
var filteredInfo = [String]()
var resultSearchController = UISearchController()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (resultSearchController.isActive) {
return filteredInfo.count
} else {
return myInfo.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if (resultSearchController.isActive) {
cell.textLabel?.text = filteredInfo[indexPath.row]
return cell
}
else {
cell.textLabel?.text = myInfo[indexPath.row]
print(myInfo[indexPath.row])
return cell
}
}
func updateSearchResults(for searchController: UISearchController) {
filteredInfo.removeAll(keepingCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (myInfo as NSArray).filtered(using: searchPredicate)
filteredInfo = array as! [String]
self.tableView.reloadData()
}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
resultSearchController = ({
let seachController = UISearchController(searchResultsController: nil)
seachController.searchResultsUpdater = self
seachController.dimsBackgroundDuringPresentation = false
seachController.searchBar.sizeToFit()
tableView.tableHeaderView = seachController.searchBar
return seachController
})()
tableView.reloadData()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment