首页 > 解决方案 > Swift tableview 单元格不使用不同的标识符保存状态

问题描述

我对细胞的重复使用感到非常困惑。

我有一张桌子,每个单元格都是一个带有开关的单元格。如果我切换开关,我将该单元格的背景颜色设置为不同的颜色。但是,每次我滚动这些更改都不会持续存在。

我正在继承 UITalbeViewCell 来创建我自己的自定义单元格。每个单元格都有不同的标识符。但是,当我滚动表格时,我对单元格所做的任何更改仍然无法保存。我读过类似的问题,但没有一个有效。一些我建议的子类,一些建议使用不同的标识符,我也这样做了......

这是我的表格视图的代码。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let key = Array(dataSource[indexPath.section].keys)[indexPath.row]

    let cell = CellWithSwitch.init(style: .subtitle, reuseIdentifier: key)
    cell.awakeFromNib()

    let val = Array(dataSource[indexPath.section].values)[indexPath.row]
    cell.switchView?.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

    if let index = key.firstIndex(of: "."){
        cell.textLabel?.text = String(key.suffix(from: key.index(index, offsetBy: 1)))
    }else{
        cell.textLabel?.text = key;
    }
    cell.switchView?.setOn(val, animated: true)
    return cell
}

标签: swiftuitableview

解决方案


您可以更改数组switchChange

让我将数组用于切换,如下所示:

var arrSwitch = [false,false,false,false,false,false,false,false,false,false]

下面是我的cellForRowAt方法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
        cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
        cell. switchView.tag = indexPath.row
        cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
        return cell
    }

这是我的onSwitchTap行动

@IBAction func onSwitchTap(_ sender: UISwitch) {
        self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]
    }

现在在滚动时,它将保留您所做的最后更改。


推荐阅读