import UIKit
class ViewController: UIViewController {
var tableView: UITableView!
//搜索控制器
var searchController = UISearchController()
//原始数组
let someArray = ["aoxiaomi","A Private Conversation ","Breakfast Or Lunch","Please Send Me A Card","An Exciting Trip","No Wrong Numbers","Percy Buttons","Too Late","The Best And The Worst","A Cold Welcome","Not For Jazz"]
//搜索数组
var searchedArray = [String](){
didSet {self.tableView.reloadData()}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView = UITableView(frame: CGRectMake(0, 20, view.bounds.width, view.bounds.height-20),style: .Plain)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.view.addSubview(self.tableView)
self.searchController = {
let c = UISearchController(searchResultsController: nil)
c.searchResultsUpdater = self
c.hidesNavigationBarDuringPresentation = false
c.dimsBackgroundDuringPresentation = false
c.searchBar.searchBarStyle = .Minimal
c.searchBar.sizeToFit()
self.tableView.tableHeaderView = c.searchBar
return c
}()
self.tableView.reloadData()
}
}
import UIKit
extension ViewController:UITableViewDataSource{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active {//被点击
return self.searchedArray.count
}else{//没点击
return self.someArray.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
if searchController.active {
cell.textLabel!.text = self.searchedArray[indexPath.row]
}else {
cell.textLabel!.text = self.someArray[indexPath.row]
}
return cell
}
}
extension ViewController:UITableViewDelegate{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
extension ViewController:UISearchResultsUpdating{
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchedArray.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = NSArray(array: self.someArray).filteredArrayUsingPredicate(searchPredicate)
self.searchedArray = array as! [String]
}
}