Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh UITableView in Swift

I have a problem with refreshing my custom UITableView inside an UIViewController.

When appear the tableView has all its cell with a clear backgroundcolor. I have a "start" button above and when I click on it I want to have all the cell in another color.

I have specified the rules in:

    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if self.status == "start" {

        if indexPath != self.currentIndexPath {
            cell.backgroundColor = UIColor(red: 0  , green: 0, blue: 0, alpha: 0.5)
        } else {
            cell.backgroundColor = UIColor.clearColor()
        }

    } else {
        cell.backgroundColor = UIColor.clearColor()
    }
}

In the "start" action button, I call: self.tableView.reloadData

@IBAction func startAction(sender: AnyObject) {
self.currentIndexPath = NSIndexPath(forRow: 0, inSection: 0)

self.status = "start"
self.tableView.reloadData()
}

But it's not working very well as I must scroll to update the background color.

I tried to use the self.tableView.reloadRowsAtIndexPaths method. But the result is the same.

I always must scroll the tableView to update the background color or some images.

Where am I wrong ?

like image 970
Jojo Avatar asked Feb 22 '16 11:02

Jojo


People also ask

How do you refresh a table view?

If you want to reload your table view while also saving and restoring any selections, you should take a copy of the indexPathsForSelectedRows property before the reload, then re-apply those selections after calling reloadData() . With that in place, you can now call yourTableView.


2 Answers

Replace your call to reloadData with:

DispatchQueue.main.async { self.tableView.reloadData() }
like image 151
Richard Fairhurst Avatar answered Oct 09 '22 01:10

Richard Fairhurst


You should probably put your logic inside the cellForRowAtIndexPath delegate method, this will get called when you reload the table.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath)
    if self.status == "start" {
        if indexPath != self.currentIndexPath {
            cell.backgroundColor = UIColor(red: 0  , green: 0, blue: 0, alpha: 0.5)
        } else {
            cell.backgroundColor = UIColor.clearColor()
        }
    } else {
        cell.backgroundColor = UIColor.clearColor()
    }
    return cell
}

As I can't see your current implementation of this method I have just guessed at your dequeuing of the cell, you may need to change this slightly, If you can post this code in your question I can help.

like image 32
Wez Avatar answered Oct 09 '22 00:10

Wez