Alexandre Gaubil
Alexandre Gaubil

Reputation: 199

How to know which cell was tapped in tableView using Swift

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
}

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?

Thank you in advance.

EDIT:

I understood what is falsing my results.

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?

Here is the code for my 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
            }
        }
    }

Thanks again.

Upvotes: 0

Views: 3974

Answers (1)

Majed Dkahellalah
Majed Dkahellalah

Reputation: 408

try this

var selectedCell: IndexPath

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

if you want use IndexPath

self.selectedCell?.row

Upvotes: 3

Related Questions