2017-08-03 70 views
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!) 
    } 
} 
+0

您需要在'filterContentForSearchText'中显示代码。最可能的原因是由于调用的异步特性,在更新allSearchResultOfferings之前调用了reloadData。 – Michael

+0

你应该在主线程中调用'reloadData()'。 'DispatchQueue.main.async {tableView。 reloadData()}' –

+0

@NandiinBao是的,我调用mainthread中的reloadData(),一旦我从api调用得到响应! – itachi

回答

0

误报 - 必须退出Xcode,清理并重建项目。它现在像一种魅力。