swift2 – Swift – Clear TableView
发布时间:2020-12-14 05:22:00 所属栏目:百科 来源:网络整理
导读:我有一个搜索,它下载一个 JSON文件并在TableView中显示结果.如果用户搜索某些内容并获取结果列表,则搜索返回0结果的其他内容.第一组结果仍然在TableView中.我想在每次新搜索开始时清除TableView以防止发生这种情况.我已经尝试将数据源设置为nil并重新加载Tab
我有一个搜索,它下载一个
JSON文件并在TableView中显示结果.如果用户搜索某些内容并获取结果列表,则搜索返回0结果的其他内容.第一组结果仍然在TableView中.我想在每次新搜索开始时清除TableView以防止发生这种情况.我已经尝试将数据源设置为nil并重新加载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 }
不要使用可选类型.
声明一个非可选的空数组. var searchResults : [[String : Any]]() 那么numberOfRowsInSection就可以了 override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return searchResults.count } 要清除表视图写入 searchResults.removeAll() tableView.reloadData() 没有打包,没有检查零,没有问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |