1
我正在實現一個像Instagram一樣的搜索頁面 - 這樣,當您轉到搜索選項卡時,您會看到趨勢搜索(包含動態部分)等,但是當您開始在搜索框中輸入內容時,趨勢搜索會消失,並顯示搜索結果。iOS UITableView不會在搜索時重新加載數據
我這樣做,但它似乎並沒有工作。 A)當我搜索某些東西時(我記錄api調用的響應 - 我確實獲得了正確的數據),沒有顯示任何結果。 B)我不回去,以顯示趨勢的結果,即使以後我打取消(同樣,我在cancelSearch動作打印,該功能被稱爲是肯定的)
這裏是我的代碼的簡化版本:
class SearchVC: UITableViewController {
let searchController = UISearchController(searchResultsController: nil)
var sections = [String]()
var allTrendingOfferings = [[OfferingModel]]()
var allSearchResultOfferings = [OfferingModel]()
override func viewDidLoad() {
super.viewDidLoad()
sections = // data from backend
allTrendingOfferings = // data from backend
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (searchController.isActive) {
return ""
}
return self.sections[section]
}
override func numberOfSections(in tableView: UITableView) -> Int {
if (searchController.isActive) {
return 1
}
return self.sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (searchController.isActive) {
return allSearchResultOfferings.count
}
return allTrendingOfferings[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "offeringCell", for: indexPath) as! SeachTVCell
if (searchController.isActive) {
let offering = allSearchResultOfferings[indexPath.row]
} else {
let offering = allTrendingOfferings[indexPath.section][indexPath.row]
}
// configure cell and
return cell
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
allSearchResultOfferings = // data fetched from backend
self.tableView.reloadData() // done asynchronously (after receiving data)
}
func searchCancel() {
self.tableView.reloadData()
}
}
extension SearchVC: UISearchResultsUpdating {
@available(iOS 8.0, *)
func updateSearchResults(for searchController: UISearchController){
if !searchController.isActive {
searchCancel()
}
filterContentForSearchText(searchText:searchController.searchBar.text!)
}
}
您需要在'filterContentForSearchText'中顯示代碼。最可能的原因是由於調用的異步特性,在更新allSearchResultOfferings之前調用了reloadData。 – Michael
你應該在主線程中調用'reloadData()'。 'DispatchQueue.main.async {tableView。 reloadData()}' –
@NandiinBao是的,我調用mainthread中的reloadData(),一旦我從api調用得到響應! – itachi