如何知道使用 Swift 在 tableView 中点击了哪个单元格 [英] How to know which cell was tapped in tableView using Swift

查看:31
本文介绍了如何知道使用 Swift 在 tableView 中点击了哪个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a tableView to display a list of names. When the user taps on one of the cells, a popup should come up showing more detail. I am using this function to check what cell the user has tapped.

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 之间的随机数(我目前显示了三个单元格).

Unfortunately, it seems to give give back random numbers between 0 and 2 (I currently have three cells that are displayed).

你知道我怎么知道哪个单元格被窃听了吗?

Do you know how I could know which cell was tapped?

提前致谢.

我明白什么是我的结果造假.

I understood what is falsing my results.

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

I am using this function to push which cell is selected to another view controller (named ConversationViewcontroller). But, the segue fonction is called before the tableView function, and so the segue pushes the previously selected cell. How could I correct this?

这是我的转场代码:

//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
            }
        }
    }

再次感谢.

推荐答案

试试这个

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

if you want use IndexPath

self.selectedCell?.row

这篇关于如何知道使用 Swift 在 tableView 中点击了哪个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆