2

我制作了一个列出 UITableView 中项目的应用程序。当我选择项目并向下滚动直到它们离开屏幕时,它们将在视觉上被取消选择,这意味着:

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

然而,系统本身确实知道选择了什么,没有选择什么。

代码:

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
    }

关于如何解决这个问题的任何想法?

提前致谢。

4

1 回答 1

1

在“didSelectRowAtIndexPath”上,直接在单元格上更改 backgroundColor 和 imgCarName。

当您滚动时,您的单元格会被重复使用!这意味着同一个单元格被破坏并用于呈现新内容。

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

于 2015-03-05T14:57:07.483 回答