【问题标题】:Swift 5 | didSelectRowAt is selecting two cells at the same time斯威夫特 5 | didSelectRowAt 同时选择两个单元格
【发布时间】:2020-06-02 13:52:08
【问题描述】:

我正在做一个屏幕,其中有一个带有开关的单元格列表,如下图所示; 我有一个结构,其中保存单元格的标签和开关状态值。这个结构体被加载到:var source: [StructName] = [],然后源值被赋予 UITableView 单元格。

问题是当触摸一个单元格时,函数:func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)change multiples cells 同时切换状态。 我尝试通过实现以下功能来解决这个问题:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
    for n in 0..<source.count{ // This loop search for the right cell by looking at the cell label text and the struct where the state of the switch is saved
        if cell.label.text! == source[n].Label{
            // If the label text is equal to the position where the values is saved (is the same order that the cells are loaded in the UITableView) then a change the state of the switch
            let indexLabel = IndexPath(row: n, section: 0)
            let cellValues = tableView.cellForRow(at: indexLabel) as! CustomTableViewCell
            if cellValues.switchButton.isOn {
                cellValues.switchButton.setOn(false, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            } else {
                cellValues.switchButton.setOn(true, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            }
            break
        }
    }

虽然将正确的值保存到开关状态数组(源)中,但多个开关的视觉状态也会发生变化,即使从未接触过的单元格也是如此。

如何更改我的代码以选择和更改触摸的单元格?

【问题讨论】:

    标签: ios swift uitableview swift5 uiswitch


    【解决方案1】:

    您不应存储/读取单元格中任何内容的状态。 但首先要做的是:

    • 为什么要循环遍历所有值?您应该可以通过indexPath.row 直接访问数据模型中的行
    • 您应该只修改模型数据,而不是单元格
    • 然后您告诉表格视图重新加载单元格,然后它会要求模型显示正确的数据。

    我建议如下:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    
        let row = indexPath.row
        source[row].valor.toggle()
        tableView.reloadRows(at:[indexPath], with:.automatic)
    }
    

    【讨论】:

    • at.row 到底代表什么?我假设那是 indexPath。我仍然得到相同的结果,一些底部单元格仍然在改变而没有被触摸。
    • 您需要将单元格的“状态”存储在数据模型中。发生的事情是 tableView 重用了单元格,并且由于您没有单独的事实,即单元格被重用并打开它。注意source[row].valor.toggle() 如果您的数据源是struct,请记住结构是值类型。
    • @Renan 你是对的,这是一个复制粘贴问题;它不应该是at,而是indexPath。如果您遇到其他问题,您应该向我们展示 cellForRowAtIndexPath 实现。
    猜你喜欢
    • 2017-07-22
    • 2017-03-24
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多