【问题标题】:Swift UITableView visually deselects cells on scrollSwift UITableView 在滚动时视觉上取消选择单元格
【发布时间】:2015-05-06 23:50:48
【问题描述】:

我制作了一个在 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
    }

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

提前致谢。

【问题讨论】:

    标签: uitableview swift scroll deselect


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多