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

标签 swift toggle checkmark

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

我在 this 中找到了一个函数类似但较旧的线程。由于 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它一次只能选择一个单元格:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.allowsMultipleSelection = false
}

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

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

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)。这里是如何做的,你应该很好,如果没有让我知道,我可以再次编辑。

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:仅对最后选定的单元格将复选标记切换为 ON - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516401/

相关文章:

ios - 在展开可选值时发现 nil - spriteKit

swift - 在文本字段中快速进行 3D 触摸时关闭编辑菜单

arrays - 如果选中标记 - 将对象添加到数组 [SWIFT]

objective-c - 单元格 accessorytype 不会在 [tableview reloadData] 上重新加载

json - 可以不存档的情况下保存json数据吗

ios - swift : How to save latitude and longitude to use in another swift file

html - 在没有 jquery 的情况下在滚动条上切换标题内容

android - 如何激活列表 Activity 中的复选标记?

reactjs - 在 react 状态中切换 bool 值

forms - 在 RAD studio 2010 中切换表单/单元 View (F12 键)