Я реализовал функцию поиска в своем приложении для просмотра таблиц. Единственная проблема заключается в том, что когда я нажимаю на строку поиска, а затем нажимаю «Отмена», ячейки, которые ранее отображались, исчезли. Это все акции; ничего не изменилось. Когда я добавил контроллер отображения поиска, я добавил его из раскадровки без настройки.
import UIKit
class DataTableExercisesTableViewController: UITableViewController, UISearchResultsUpdating {
let exercises = ["Abs", "Arms", "Back", "Chest", "Legs", "Shoulders", "Triceps"]
var filteredTableData = [String]()
var resultSearchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
resultSearchController.searchResultsUpdater = self
resultSearchController.dimsBackgroundDuringPresentation = false
resultSearchController.searchBar.sizeToFit()
resultSearchController.hidesNavigationBarDuringPresentation = false
tableView.tableHeaderView = resultSearchController.searchBar
return controller
})()
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.active {
return filteredTableData.count
} else {
return exercises.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ExerciseCell", forIndexPath: indexPath)
// Configure the cell...
if (self.resultSearchController.active) {
cell.textLabel?.text = filteredTableData[indexPath.row]
return cell
}
else {
cell.textLabel?.text = exercises[indexPath.row]
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (exercises as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}