Swift:仅对最后选定的单元格将复选标记切换为打开 - 不起作用

Swift: Toggling checkmark to ON for last selected cell only - not working

我在一个部分中有给定数量的单元格。我的目标是只让最后选定的单元格显示复选标记。其他单元格不应该。

我在 类似但较旧的线程中找到了一个函数。由于 Swift 3.0.

中的更改,我对其进行了一些修改(我敢打赌问题出在这里)

正如下面所写,对我来说,该功能无法正常工作。只有该部分中的最后一个单元格(不是最后选择的,而是部分中的最后一个)才会获得复选标记。但是我不知道为什么不。

完整函数如下:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let section = indexPath.section
    let numberOfRows = tableView.numberOfRows(inSection: section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.accessoryType = row == indexPath.row ? .checkmark : .none
        }
    }
}

通过打印出这些值,我可以看到下面这条语句的计算结果为真,这是有道理的。但是复选标记不会被切换。

    cell.accessoryType = row == indexPath.row ? .checkmark : .none

谢谢!

首先告诉你的 tableview 它一次只能 select 一个单元格:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.allowsMultipleSelection = false
}

然后,让我们分析您的代码,您将获取当前单元格所在的部分 selected 并计算该特定部分中的行数。您迭代该部分的行并检查您是否在给定的 indexPath 处有一个单元格(我猜它总是评估为 true 因为您总是在该 indexPath 处有一个单元格,您没有根据您的值设置条件for循环)。然后,如果 for 循环中的行等于用户当前 select 编辑的单元格行,则告诉单元格有一个复选标记。 在编写您的函数时,没有理由只有该部分的最后一个会得到复选标记,但您把事情复杂化了。

您的单元格是用以下方法绘制的,附件最初也是如此。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "YourCell", for: indexPath)

    cell.textLabel?.text = "your text"

    cell.accessoryType = cell.isSelected ? .checkmark : .none
    // cell.selectionStyle = .none if you want to avoid the cell being highlighted on selection then uncomment

    return cell
  }

那你可以直接说附件类型在tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)中应该是.checkmark,在tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)中是.none。这是怎么做的,你应该很好,如果不让我知道,我可以重新编辑。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .checkmark
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .none
}

Swift 4.x
Xcode12

func viewDidLoad() {
 tableView.allowsMultipleSelection = false
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tvAmbientSoundTableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tvAmbientSoundTableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}