我有一个搜索,它下载一个
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()
没有打包,没有检查零,没有问题.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。