我一直在嘗試在應用程序中實現UISearchController,並且作爲參考,我正在遵循this教程。該教程涵蓋了比我需要的多一點(如範圍),所以我只是剔除它,但是當我運行我的測試應用程序時,搜索無效。當我在搜索欄中輸入內容時,無論我是否按下「搜索」,它只會過濾輸入的第一個字符的結果。例如,如果我輸入「海豚」,它只會顯示包含「d」的結果。通過打印updateSearchResultsForSearchController
,我確認它只被調用一次。但是,如果我刪除搜索欄中的所有內容,結果會回到未過濾的狀態,如果我再次鍵入某個內容,它將(再次)僅對第一個字符進行過濾。iOS updateSearchResultsForSearchController只調用一次
我也嘗試瞭解決方法建議here,但問題仍然存在。這是我的代碼:
class SearchController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
let data = [
"bottlenose dolphin": 111,
"manta ray": 172,
"humphead wrasse": 388,
"Commerson's dolphin": 19
// etc.
]
var results = [String: Int]()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return results.count
} else {
return data.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
if searchController.active && searchController.searchBar.text != "" {
let index = results.startIndex.advancedBy(indexPath.row)
cell.textLabel!.text = results.keys[index]
} else {
let index = data.startIndex.advancedBy(indexPath.row)
cell.textLabel!.text = data.keys[index]
}
return cell
}
func search(searchText: String) {
let temp = data.filter({(element: (String, Int)) -> Bool in
return element.0.lowercaseString.containsString(searchText.lowercaseString)
})
for element in temp { results[element.0] = element.1 }
tableView.reloadData()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
updateSearchResultsForSearchController(searchController)
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
search(searchController.searchBar.text!)
}
}
有我略讀指導教程時錯過了一步的機會,但我已經經歷了好多次,看起來也沒有用。我怎樣才能使搜索工作正常?
編輯:我也注意到有時搜索會彈出結果,甚至不包含查詢的第一個字符。例如,使用不同的一組數據,搜索「J」彈出「硅谷」...
我不敢相信我忽略了那樣簡單的事!現在搜索起作用了,謝謝! – Technicolor
面臨同樣的問題。感謝bluedome –