滚动时 UISwitch 正在更改其他单元格上的状态

UISwitch is changing state on other cell when scroll

我的表格视图是这样的

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 200
}

我的 tableviewcell 看起来像这样

class Cell: UITableViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

当我更改任何单元格上的开关状态并滚动时。另一个单元格的开关会在其他单元格滚动时定期更改状态。请帮忙

正确处理每个单元格的开关控制,

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

以便当单元格出队时,它会正确处理每个单元格的 switchControl

解法: 当您更改单元格的开关控件状态时,将 indexPath 保存在某处,以便当您在表视图 cellForRowAt indexPath 中遍历此 indexPath 时,您会再次设置该开关状态,否则设置默认状态

您需要为每个开关设置带有状态的数据数组,并在您的 didSelect 方法中更改开关的数据模型,然后在 cellForRow 中从数组获取开关状态并且您的 viewController 需要是 SwitchControlDelegate

class UIViewController:SwitchControlDelegate{

    var array = [Bool](count: 200, repeatedValue:false)

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
    cell.switchControl.isOn = array[indexPath.row]
    cell.switchDelegate = self
    cell.index = indexPath.row
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 200
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    array[indexPath.row] = !array[indexPath.row]
}

func switchChangeStateWithIndex(index:Int){
    array[index] = !array[index]
}

这将在您单击单元格时更改开关状态,如果您需要在更改开关控件时更改状态,您将需要委托更新 viewController

中的数据模型

在您的单元格文件中:

    protocol SwitchControlDelegate: class {
        func switchChangeStateWithIndex(index:Int)
    }

    class Cell: UITableViewCell {

        var index:Int = 0
        weak var switchDelegate: SwitchControlDelegate?
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }

        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)

            // Configure the view for the selected state
        }

        @IBAction func valueChanged(_ sender: AnyObject) {
             switchDelegate?.switchChangeStateWithIndex(index:index)
        }

}

您需要使用此函数 valueChanged 匹配开关控件的动作值更改,因此每次更改开关状态时,单元格都需要调用 func value Changeed