swift2 – Swift – Clear TableView

我有一个搜索,它下载一个 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()

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...