swift2 – Swift – Clear TableView

前端之家收集整理的这篇文章主要介绍了swift2 – Swift – Clear TableView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个搜索,它下载一个 JSON文件并在TableView中显示结果.如果用户搜索某些内容获取结果列表,则搜索返回0结果的其他内容.第一组结果仍然在TableView中.我想在每次新搜索开始时清除TableView以防止发生这种情况.我已经尝试将数据源设置为nil并重新加载TableView但它无法正常工作.这就是我所拥有的:
  1. var searchResults : [[String : AnyObject]]? = nil
  2.  
  3. func searchBarSearchButtonClicked(searchBar: UISearchBar) {
  4. print("DEBUG: searchBarSearchButtonClicked")
  5. if searchBar.text > "" {
  6.  
  7. //--- This isn't working ---
  8. searchResults = nil
  9. tableView.reloadData()
  10. //--------------------------
  11.  
  12. activityIndicator.startAnimating()
  13.  
  14. dbSearcher.startSearch(searchBar.text!) { (results) -> () in
  15. self.searchResults = results
  16. self.activityIndicator.stopAnimating()
  17. self.tableView.reloadData()
  18. }
  19.  
  20. searchBar.endEditing(true)
  21. }
  22. }
  23.  
  24. override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
  25. if searchResults != nil {
  26. print("DEBUG: Result count \(searchResults!.count)")
  27. return searchResults!.count
  28. } else {
  29. print("DEBUG: Result count 0") //I don't see this other than when the ViewController first loads
  30. return 0
  31. }
  32.  
  33. }
  34.  
  35. override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  36. let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("searchResult")!
  37. cell.textLabel?.text = searchResults![indexPath.row]["Title"] as? String
  38. cell.detailTextLabel?.text = searchResults![indexPath.row]["Year"] as? String
  39.  
  40. //Display cover
  41. let imageURL = searchResults![indexPath.row]["Poster"] as? String
  42. if imageURL != "N/A" {
  43.  
  44. if let cover : UIImage = searchResults![indexPath.row]["Image"] as? UIImage {
  45. cell.imageView?.image = cover
  46. } else {
  47. //Use default cover while the correct image downloads
  48. //cell.imageView?.image = DEFAULT_COVER
  49. downloadCover(imageURL!,tableViewRow: indexPath.row)
  50. }
  51.  
  52. } else {
  53. //Use default cover
  54. //cell.imageView?.image = DEFAULT_COVER
  55. }
  56.  
  57. return cell
  58. }
不要使用可选类型.
声明一个非可选的空数组.
  1. var searchResults : [[String : Any]]()

那么numberOfRowsInSection就可以了

  1. override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
  2. return searchResults.count
  3. }

要清除表视图写入

  1. searchResults.removeAll()
  2. tableView.reloadData()

没有打包,没有检查零,没有问题.

猜你在找的Swift相关文章