Darin Darin - 2 years ago 137
Swift Question

Swift tableview cell reuse issue

I am drawing a blank this morning and can use a little guidance.

I am populating a tableview with an array of dictionaries using a custom table cell. One of the key value pairs in the dictionary is [“Time”] which is represented as such in the array of dicts:

"time": "12am",
"time": “1am",
"time": “2am",
"time": “3am” and so on….

Here is what I would like to do.

If the current time of day is 1am (for example) I would like to change that cell’s background color. I have this partially working using the code pasted below. When the table view loads the proper cell is being highlighted however when I scroll up and down through the table view I see that other rows are being highlighted. I am assuming that this has something to do with how the cells are being reused.

Additional information:
1) “items” is my array of dictionaries
2) currentTime() is just a little function that returns the current time of day in this format (“1pm”)

Can someone point me in the right direction ?

Kind regards,

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:schedTableCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! schedTableCell
cell.selectionStyle = .None

// Highlight row where time value is equal to current time - THIS NEEDS WORK
let showTime = self.items[indexPath.row]["time"] as! String
if showTime == currentTime() {
cell.backgroundColor = UIColor.greenColor()

cell.showTime.text = self.items[indexPath.row]["time"] as? String
cell.showName.text = self.items[indexPath.row]["show"] as? String
cell.showHost.text = self.items[indexPath.row]["host"] as? String

return cell

Answer Source

Indeed, it's a reuse problem. When you do this cell.backgroundColor = UIColor.greenColor(), you change the cell background color. But when the cell is reused, you do not reset the background color, so it stays green ! You can fix it like this (if white is your normal color):

   if showTime == currentTime() {
        cell.backgroundColor = UIColor.greenColor()
    } else {
        cell.backgroundColor = UIColor.whiteColor()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download