UITableviewCell只切换一个自定义复选标记状态不起作用 - Swift 3

时间:2017-04-21 15:47:29

标签: ios swift uitableview

我已审核this link,解决方案对我不起作用。

我正在尝试选择一行,当我选择它时,它会在标签上添加一个复选标记。如果在存在复选标记的情况下选择了另一行,则会取消选中存储在selectedIndexPath变量中的前一行。

它在开始时工作,但是当多次滚动浏览桌面视图时,我偶尔会看到一个不应该在此图像中指示的单元格:

enter image description here

当用户选择单元格时我正在做什么:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {
        let customCell = customCellData[indexPath.row]
        customCell.toggleSelected()
        cell.configureCheckmark(with: customCell)
    }

    if let oldIndexPath = selectedIndexPath, let cell = tableView.cellForRow(at: oldIndexPath) as? CustomCell, oldIndexPath.row != indexPath.row {
        let customCell = customCellData[oldIndexPath.row]
        customCell.toggleSelected()
        cell.configureCheckmark(with: customCell)
    }


    if let selected = selectedIndexPath, selected.row == indexPath.row {
        selectedIndexPath = nil
        tableView.deselectRow(at: indexPath, animated: true)
    } else {
        selectedIndexPath = indexPath
    }

}

和in for cellForRowAt :(检查selectedIndexPath和模型中的状态是多余的吗?)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
    let customCell = customCellData[indexPath.row]
    cell.customCell = customCell
    if selectedIndexPath == indexPath {
        cell.checkLabel.text = "✔️"
    } else {
        cell.checkLabel.text = ""
    }

    return cell
}

最后在CustomCell中:

var customCell: CustomCell? {
    didSet {
        if let customCell = customCell {
            configureCheckmark(with: customCell)
        }
    }
}

func configureCheckmark(with customCell: CustomCellData) {
    if customCell.isSelected {
        checkLabel.text = "✔️"
    } else {
        checkLabel.text = ""
    }
}

CustomCellData我按如下方式切换状态:

class CustomCellData {
    var isSelected = false

    func toggleSelected() {
       isSelected = !isSelected
    }
}

我正在摸不着头脑,不确定该怎么做,任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是将didSelectRowAt缩减为

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
    selectedIndexPath = indexPath
    tableView.reloadData()
}

这会正确更新所有可见单元格。

或更复杂的版本,仅更新受影响的行并检查单元格是否已被选中

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if selectedIndexPath != indexPath  {
        let indexPathsToReload = selectedIndexPath == nil ? [indexPath] : [selectedIndexPath!, indexPath]
        selectedIndexPath = indexPath
        tableView.reloadRows(at: indexPathsToReload, with: .none)
    } else {
        selectedIndexPath = nil
        tableView.reloadRows(at: [indexPath], with: .none)
    }
}

cellForRowAt中的代码完成其余的工作。