问题
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.
回答1:
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.
回答2:
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)
...
}
来源:https://stackoverflow.com/questions/48466713/passing-selected-row-data-to-next-view-controller-swift-3