Reputation: 459
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 ?
Upvotes: 7
Views: 21178
Reputation: 814
Replace your call to reloadData with:
DispatchQueue.main.async { self.tableView.reloadData() }
Upvotes: 15
Reputation: 961
Instead of adding your codes on WillDisplayCell add in cellForRowAtIndexPath
@IBAction func startAction(sender: UIButton)
{
let buttonPosition : CGPoint = sender.convertPoint(CGPointZero, toView: self.tableview )
self.currentIndexPath = self.tableview.indexPathForRowAtPoint(buttonPosition)!
self.status = "start"
self.tableView.reloadData()
}
Upvotes: 0
Reputation: 5674
You've got the logic in the wrong place. willDisplayCell
is called just before the cell is drawn which is why it makes sense that you're seeing the change when you scroll. Calling reloadData
is going to call cellForRowAtIndexPath
so you should move your logic to that method.
Upvotes: 0
Reputation: 10712
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.
Upvotes: 1