我有一个搜索下载一个JSON文件并在TableView中显示结果。如果用户搜索某些内容并获取结果列表,则搜索返回0结果的其他内容。第一组结果仍然在TableView中。我想在每次新搜索开始时清除TableView以防止发生这种情况。我已经尝试将数据源设置为零,并重新加载TableView,但它不起作用。以下是我的:Swift - 清除TableView
var searchResults : [[String : AnyObject]]? = nil
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
print("DEBUG: searchBarSearchButtonClicked")
if searchBar.text > "" {
//--- This isn't working ---
searchResults = nil
tableView.reloadData()
//--------------------------
activityIndicator.startAnimating()
dbSearcher.startSearch(searchBar.text!) { (results) ->() in
self.searchResults = results
self.activityIndicator.stopAnimating()
self.tableView.reloadData()
}
searchBar.endEditing(true)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchResults != nil {
print("DEBUG: Result count \(searchResults!.count)")
return searchResults!.count
} else {
print("DEBUG: Result count 0") //I don't see this other than when the ViewController first loads
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("searchResult")!
cell.textLabel?.text = searchResults![indexPath.row]["Title"] as? String
cell.detailTextLabel?.text = searchResults![indexPath.row]["Year"] as? String
//Display cover
let imageURL = searchResults![indexPath.row]["Poster"] as? String
if imageURL != "N/A" {
if let cover : UIImage = searchResults![indexPath.row]["Image"] as? UIImage {
cell.imageView?.image = cover
} else {
//Use default cover while the correct image downloads
//cell.imageView?.image = DEFAULT_COVER
downloadCover(imageURL!, tableViewRow: indexPath.row)
}
} else {
//Use default cover
//cell.imageView?.image = DEFAULT_COVER
}
return cell
}
我试过你重置表视图的方式,它适用于我。表被清空。在你的问题中,你写下你设置你的dataSource为零。你还在别的地方做过吗? – joern
不,我只在searchBarSearchButtonClicked(...)中执行此操作。当我说我将它设置为零时,我的意思是将tempDict创建为零字典并设置searchResults = tempDict。我确实试图做searchResults = nil,但它给了我一个错误。 – Daniel
尝试设置'searchResults = nil'时会出现什么样的错误?它不应该导致错误。 – joern