首页 > 解决方案 > 如何快速按下所选单元格的IndexPath

问题描述

我一直在尝试获取当前选定行的 IndexPath。我一直在使用这个功能:

    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPathForSelection: IndexPath) {
            print(SavedColors.SavedColorsList[indexPathForSelection.row].Name)
    }

问题是它给了我刚刚取消选择的单元格的 IndexPath。如果我按下第一个单元格,什么也不会发生。如果我然后按第二个单元格,它会在第一个单元格的 indexPath 中打印“0”,依此类推。我想在按下单元格后立即获取索引路径。我该怎么做呢?

Said another way: the function is called when the selection is switched to another cell, but not when a cell is selected. 我希望用户点击,并激活该功能。相反,当您点击时,什么都不会发生,直到您点击另一个不同的单元格。我怎样才能解决这个问题?

我不知道这是否相关,但该self.tableView.deselectSelectedRow(animated: true)功能也没有做任何事情......

谢谢

标签: swiftuitableviewdidselectrowatindexpath

解决方案


您需要使用 didSelect 而不是 deSelect

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPathForSelection: IndexPath) {
            print(SavedColors.SavedColorsList[indexPathForSelection.row].Name)
    }

.

DidSelect 在您选择一个单元格时调用,而在您取消选择一个单元格时调用 deSelect ... 所以在编写这些函数时要小心,快乐编码 =)


推荐阅读