将选定的行数据传递给下一个View Controller Swift 3

时间:2018-01-26 17:40:20

标签: ios xcode swift3

我是Swift Programming的新手,我遇到了问题。所以我想要做的是当用户选择表中的行然后我想获取所选行的标题然后将其传递给下一个视图控制器。这是我的第一个视图控制器的代码:

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)
}

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果您使用的是segue,则需要在prepare(for segue: UIStoryboardSegue, sender: Any?)中传递数据。因此,请将didSelectRowAt更改为此:

newIndex = indexPath.row

let selectedMessage = messageArray[indexPath.row]

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

然后覆盖prepareForSegue

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

您的方法无效,因为您自己创建了一个新的VC,这与实际呈现的VC不同。

答案 1 :(得分:0)

您可以尝试这样的事情:

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

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