參考資料:IOS 10程式設計超進化攻略 Simon NG著
* searchController = UISearchController(searchResultsController:nil)
* searchController.searchResultsUpdater = self
* tableView.tableViewHeaderView = searchController.searchBar
說明:
let searchResultsController = UITableViewController()
var searchController:UISearchController?
在ViewDidLoad()中寫入:
searchController = UISearchController(searchResultsController: searchResultsController)
tableView.tableHeaderView = searchController?.searchBar
//
searchController?.searchResultsUpdater = self
讓原本的TableViewController遵守UISearchResultsUpdating這個protocol
並實作協定中的方法updateSearchResults(for searchController: UISearchController)
func updateSearchResults(for searchController: UISearchController) {
//使用者輸入要查詢的
if let searchWord = searchController.searchBar.text{
resultArray = fruitArray.filter({ (filterFruit) -> Bool in
if filterFruit.lowercased().contains(searchWord.lowercased()){
return true
}else{
return false
}
})
//讓顯示結果的tableView去reloadData
self.searchResultsController.tableView.reloadData()
}
}
完整的程式碼:
https://github.com/ethan510010/SearchBarPractice.git