在Swift3中传递数据

防羽
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {        
    let cellText: String

    //need this to give the category which is clicked to the main view controller 
    // so its sends the data from one tableview to the other
    let categories =  cat[indexPath.row]
    cellText = categories.cat!
    let choosenCategory = cellText
    self.performSegue(withIdentifier: "goToTableView", sender: choosenCategory)
    let user = "Anton"
    self.performSegue(withIdentifier: "goToTableView", sender: user)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "goToTableView")
    {
        let destination = segue.destination as? ViewController

        destination?.passedData = sender as? String
        print("open second one")
        destination?.passedUser = sender as? String
        print("Sender Vlaue: \(sender)")
    }
}

嘿!
我需要帮助。我想在tableviewcontrollers之间传递数据

我的问题是,当我在这两个之间传递数据时,它将打开两次。所以刚开始它加载ControllerpassedData事后用passedUser

我究竟做错了什么 ?

瓦瓦瓦玛

您的问题是您打了performSegue(withIdentifier:sender:)两次电话每次调用都会创建一个新的目标viewController。您需要在一个呼叫中传递设置数据。

一种选择是更新viewController中的属性以保存值,而不是将数据发送为sender

另一种方法是创建一个结构来保存值。如果您有各种类型的变量,这将很好地工作。

由于您只有两个数据,而且它们都是String,所以可以将它们传递给[String]

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

    //need this to give the category which is clicked to the main view controller 
    // so its sends the data from one tableview to the other
    let categories =  cat[indexPath.row]
    cellText = categories.cat!
    let choosenCategory = cellText
    let user = "Anton"
    self.performSegue(withIdentifier: "goToTableView", sender: [chosenCategory, user])
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToTableView"
    {
        guard let destination = segue.destination as? ViewController else { return }
        guard let info = sender as? [String] else { return }

        destination.passedData = info[0]
        destination.passedUser = info[1]
        print("Sender Value: \(sender)")
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章