Passing selected row data to next View Controller Swift 3

≡放荡痞女 提交于 2021-02-07 10:42:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!