1.定義搜索控制器變量
????var searchController: UISearchController!
2.為搜索控制器賦值
????searchController = UISearchController(searchResultsController: nil)
? ? ? ? (此函數(shù)代表僅限當(dāng)前控制器存在搜索控制器)
3.設(shè)置搜索控制器的代理
????searchController.searchResultsUpdater = self ??
4.為當(dāng)前視圖的頭部添加搜索框
? ??tableView.tableHeaderView = searchController.searchBar
tableViewCell 搜索相關(guān)數(shù)據(jù)
1.定義數(shù)組存放查找到的數(shù)據(jù)
var searchResults: [Area] = []
2.添加一個(gè)搜索依據(jù)方法
func searchFilter(text: String) {
searchResults = areas.filter({ (area) -> Bool in
return area.name!.localizedCaseInsensitiveContains(text)
})
}
3.執(zhí)行搜索方法
func updateSearchResults(for searchController: UISearchController) {
if let text = searchController.searchBar.text {
searchFilter(text: text)
tableView.reloadData()
}
}
4.根據(jù)搜索欄是否被激活顯示數(shù)據(jù)行數(shù)
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return searchController.isActive ? searchResults.count : areas.count
}
5.根據(jù)搜索欄是否被激活選擇相應(yīng)的顯示數(shù)據(jù)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let area = searchController.isActive ? searchResults[indexPath.row] : areas[indexPath.row]
}
6.根據(jù)搜索欄是否被激活選擇Cell是否能修改
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return !searchController.isActive
}
7.如果有轉(zhuǎn)場(chǎng)傳值的話需要相應(yīng)更改
搜索條美化
// 搜索條美化之后背景不變黑贸人,且可以點(diǎn)擊搜索數(shù)據(jù)
searchController.searchBar.dimsBackgroundDuringPresentation = false
// 搜索條占位符
searchController.searchBar.placeholder = ""
// 搜索條提示
searchController.searchBar.prompt
// 搜索條前景色
searchController.tintColor
// 搜索條主題樣式(默認(rèn).Prominent(突出) .Minimal(透明))
searchController.searchBar.searchBarStyle