Swift UITableView 在视觉上取消选择滚动中的单元格

Swift UITableView visually deselects cells on scroll

我制作了一个在 UITableView 中列出项目的应用程序。当我 select 项并向下滚动直到它们离开屏幕时,它们将在视觉上变为 deselected,意思是:

我们设置的复选框图像和背景颜色重置为原始状态。

然而,系统本身确实知道什么是 selected 什么不是。

代码:

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
    }

知道如何解决这个问题吗?

提前致谢。

在 'didSelectRowAtIndexPath' 上,您直接在单元格上更改 backgroundColor 和 imgCarName。

当您滚动时,您的单元格将被重复使用!意味着相同的单元格被销毁并用于呈现新内容。

要跟踪所选内容,您需要将该状态保存在单元格以外的其他位置,可能在您的 tableAvailability 对象中,或处理单元格内容的任何其他对象中。