【问题标题】:How to know which cell was tapped in tableView using Swift如何知道使用 Swift 在 tableView 中点击了哪个单元格
【发布时间】:2017-10-07 17:02:00
【问题描述】:

我正在使用 tableView 来显示名称列表。当用户点击其中一个单元格时,应该会弹出一个显示更多细节的弹出窗口。我正在使用这个函数来检查用户点击了哪个单元格。

var selectedCell: Int?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("This cell from the chat list was selected: \(indexPath.row)")
    selectedCell = indexPath.row
}

不幸的是,它似乎返回了 0 到 2 之间的随机数(我目前显示了三个单元格)。

你知道我怎么知道哪个单元格被点击了吗?

提前谢谢你。

编辑:

我明白什么是我的结果错误。

我正在使用此函数将选定的单元格推送到另一个视图控制器(名为 ConversationViewcontroller)。但是,segue 函数是在 tableView 函数之前调用的,因此 segue 会推送先前选择的单元格。我该如何纠正这个问题?

这是我的转场代码:

//SEGUE: Cell was selected: pass chatID
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "OpenChat" {
            if let toViewController = segue.destination as? ConversationViewController {
                toViewController.chatIdentifier = selectedCell
            }
        }
    }

再次感谢。

【问题讨论】:

  • 您发布的代码是正确的代码。 indexPath.row 将是您点击的行。
  • 它似乎工作正常。如果您有三个单元格,第一个 indexpath.row 将为 0,第二个为 1,然后是 2。
  • 确认将委托和数据源分配给您的表格视图
  • @Alexander OP 明确表示该表显示三行并且正在调用此委托方法,但与预期的不同。很明显,table view 的 delegate 和 dataSource 属性都设置好了。
  • @MartinMuldoon 建议数组从索引 0 开始,所以它工作正常!

标签: swift uitableview segue


【解决方案1】:

试试这个

var selectedCell: IndexPath

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("This cell from the chat list was selected: \(indexPath.row)")
    selectedCell = indexPath
}

如果你想使用 IndexPath

self.selectedCell?.row

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多