上文iOS下拉搜索的几种实现方式(一)提供了普通视图控制器
下拉搜索的几种方法。但如果我们是在导航控制器
中使用搜索,就变得简单了。因为我们可以直接使用系统提供的方案。
import UIKit
class TableViewController: UITableViewController {
var array = (0...99).map { String($0) }
override func viewDidLoad() {
super.viewDidLoad()
customizeNavigationController()
}
private func customizeNavigationController() {
self.navigationItem.leftBarButtonItem = editButtonItem
self.navigationItem.title = "Pull to Search"
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.searchController = {
let sc = UISearchController(searchResultsController: nil)
sc.searchResultsUpdater = self
sc.hidesNavigationBarDuringPresentation = true
sc.obscuresBackgroundDuringPresentation = false
sc.searchBar.delegate = self
sc.searchBar.searchBarStyle = .minimal
return sc
}()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = array[indexPath.row]
return cell
}
}
// MARK: -
extension TableViewController:UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
tableView.tableHeaderView = nil
}
}
// MARK: -
extension TableViewController:UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
array = (0...99).map({ String($0) })
.filter({
guard let text = self.navigationItem.searchController?.searchBar.text, !text.isEmpty else {
return true
}
return $0.contains(text)
})
tableView.reloadData()
}
}