Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Clear TableView

Tags:

swift2

I have a search which downloads a JSON file and displays the results in a TableView. If the user searches for something and gets a list of results, then searches for something else which returns 0 results. The first set of results is still in the TableView. I want to clear the TableView each time a new search starts to prevent that happening. I've tried setting the data source to nil and reloading the TableView but it's not working. Here's what I have:

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
}
like image 552
Daniel Avatar asked Oct 27 '15 21:10

Daniel


People also ask

How do you clear a Tableview in Swift?

So, to remove a cell from a table view you first remove it from your data source, then you call deleteRows(at:) on your table view, providing it with an array of index paths that should be zapped. You can create index paths yourself, you just need a section and row number.

What does Tableview reload data do?

Reloads the rows and sections of the table view.

What is indexPath in Tableview Swift?

indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.

Can we use Tableview in SwiftUI?

In this blog post, I'll introduce the collection view Table in SwiftUI and explain how to leverage this view on iOS 16 to build a multiplatform app. SwiftUI provides several collection views that you can use to assemble other views into dynamic groupings with complex, built-in behaviors.


1 Answers

Don't use an optional type.
Declare an non-optional empty array.

var searchResults : [[String : Any]]()

then numberOfRowsInSection can be just

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

To clear the table view write

searchResults.removeAll()
tableView.reloadData()

No unwrapping, no checking for nil, no problems.

like image 117
vadian Avatar answered Jan 03 '23 23:01

vadian