Sogyal Thundup Sherpa
Sogyal Thundup Sherpa

Reputation: 13

Passing selected row data to next View Controller Swift 3

I am new to Swift Programming and I am having problems. So what I want to do is when the user selects the row in a table then I want to grab the selected row's title and then pass it to the next View Controller. Here is my code for the First View Controller:

let senderArray = ["Sogyal","Ram"]
let messageArray = ["Hello","What's up?"]

cell.senderName.text = senderArray[indexPath.row]
cell.senderMessage.text = messageArray[indexPath.row]

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    newIndex = indexPath.row

    let selectedMessage = messageArray[indexPath.row]

    let composeVC = ComposeMessageVC()
    composeVC.usernameLbl = selectedMessage

    tableView.deselectRow(at: indexPath, animated: true)
    performSegue(withIdentifier: "goToComposeM", sender: self)
}

Any help would be appreciated.

Upvotes: 1

Views: 2160

Answers (2)

Sweeper
Sweeper

Reputation: 271635

You need to pass the data in prepare(for segue: UIStoryboardSegue, sender: Any?) if you are using a segue. So change your didSelectRowAt to this:

newIndex = indexPath.row

let selectedMessage = messageArray[indexPath.row]

tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "goToComposeM", sender: selectedMessage)

Then override prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ComposeMessageVC {
        vc.usernameLbl = sender as! String
    }
}

Your approach did not work because you are creating a new VC yourself, which is a different one from the one that is actually presented.

Upvotes: 1

Charles-olivier Demers
Charles-olivier Demers

Reputation: 1048

You can try something like this:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    ...
    let destination = YourViewController()
    destination.usernameLbl = selectedMessage
    navigationController?.pushViewController(destination, animated: true)
    ...
}

Upvotes: 0

Related Questions