Search code examples
uitableviewswiftscrolldeselect

Swift UITableView visually deselects cells on scroll


I made an app that lists items in a UITableView. When I select items and scroll down till they go off screen, they will become visually deselected, meaning:

The checkbox image we set and the backgroundcolor are reset to original state.

The system itself however, does actually know what was selected and what wasnt.

Code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell     {

        var cell:TblCell! = self.tableView.dequeueReusableCellWithIdentifier("cell") as TblCell!

        cell.lblCarName.text = tableData[indexPath.row]
        cell.lblPrice.text = tablePrice[indexPath.row]
        if (tableAvailability[indexPath.row] == "NO") {
            cell.imgCarName.image = UIImage(named: "nonselectable")
            cell.lblPrice.textColor = UIColor(red: 172/255, green: 76/255, blue: 67/255, alpha: 1);
        } else {
            cell.imgCarName.image = UIImage(named: "deselected")
        }
        cell.selectionStyle = UITableViewCellSelectionStyle.None;
        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        let cell:TblCell = tableView.cellForRowAtIndexPath(indexPath) as TblCell
        if (tableAvailability[indexPath.row] == "YES") {
            println("Row \(indexPath.row) selected")
            //var myBackView = UIView(frame: cell.frame)
            cell.backgroundColor = UIColor(red: 190/255, green: 225/255, blue: 255/255, alpha: 1);
            //cell.selectedBackgroundView = myBackView
            cell.imgCarName.image = UIImage(named: "selected")
        }
    }

    func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {
        let cell:TblCell = tableView.cellForRowAtIndexPath(indexPath) as TblCell
        if (tableAvailability[indexPath.row] == "YES") {
            println("Row \(indexPath.row) deselected")
            //var myBackView = UIView(frame: cell.frame)
            cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1);
            //cell.selectedBackgroundView = myBackView
            cell.imgCarName.image = UIImage(named: "deselected")
        }
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 70
    }

Any idea on how to fix this?

thanks in advance.


Solution

  • On 'didSelectRowAtIndexPath', you change the backgroundColor and imgCarName straight on the cell.

    When you scroll, your cell gets reused! Meaning that the same cell is destroyed and used to present new content.

    To keep track of what is selected, you need to save that state somewhere else than against the cell, maybe in your tableAvailability object, or any other object that handles the content of your cells.