Gabriel Tavares
Gabriel Tavares

Reputation: 27

Trouble getting correct element from index path in table view

I'm trying to transfer the users information to another segue but when I select the user in the table view it shows another user's information, and not the one that it suppose to be.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowUser" {
            if let indexPath = followUsersTableView.indexPathForSelectedRow {
                let user = usersArray[indexPath.row]
                let controller = segue.destination as? OtherUserProfile
                controller?.otherUser = user
                controller?.loggedInUser = loggedInUser

            }
        }
    }

Upvotes: 1

Views: 53

Answers (1)

David Cruz
David Cruz

Reputation: 3027

Maybe you should send your user in the didSelectRowAt delegate method. If not implemented, add the method:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let user = usersArray[indexPath.row]
    self.performSegue(withIdentifier: "ShowUser", sender: user)

}

then in your prepare for segue add:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowUser" {
        let controller = segue.destination as? OtherUserProfile
        controller?.otherUser = sender as! YourUserClass
        controller?.loggedInUser = loggedInUser
    }
}

Remember to CHANGE the "YourUserClass" with the actual class of the user. Maybe if using firebase it is something like FIRUser.

Hope it helps and don't hesitate to ask.

Upvotes: 1

Related Questions