Swift 3.0使用Segue在视图控制器之间传递信息

时间:2017-05-24 17:31:23

标签: swift segue uistoryboardsegue

我正在尝试将文本值从一个VC(称为secondVC)传递给另一个VC(firstVC)。第二个VC中的信息将指示firstVC中文本字段的文本值。我已经尝试过使用文档来解决这个问题,但我一定会感到非常困惑或者其他事情已经出现了 - 我无法弄明白哪个。

在我的第二个VC中:

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "saveSegue") {

        let destinationVC = segue.destination as! firstVC

        destinationVC.addressTextField.text = searchBar.text
    }
}


@IBAction func savePressed(_ sender: Any) {


    performSegue(withIdentifier: "saveSegue", sender: self)
}

在回到firstVC之后,textField没有按预期填充searchBar文本。 (searchBar文本不是nil)根据我的理解,当在secondVC中选择按钮并调用performSegue时,它还将调用prepareForSegue并设置addressTextField.text值,同时切换回firstVC。我不确定我的逻辑是否正确。

2 个答案:

答案 0 :(得分:1)

在你的FirstViewController中

    @IBAction func dismissSearchVC(_ sender: UIStoryboardSegue) {
      let sourceVC = sender.source as! viewController2
      addressTextField.text = sourceVC.searchBar.text
}

在你的secondViewController

var searchedText = ""


@IBAction func savePressed(_ sender: Any) {
    performSegue(withIdentifier: "saveSegue", sender: self)
}

现在连接你的viewController以退出顶部并添加一个标识符作为saveSegue到segue并从下拉列表中选择dismissSearchVC

enter image description here

enter image description here

然后从这里选择您的segue enter image description here

现在选择"展开segue到DismissSearchVC"并在属性检查器中添加标识符..

答案 1 :(得分:0)

我怀疑由于segue而没有发生从一个视图控制器到另一个视图控制器的转换,而是由于按钮的连接而发生这种转换。

删除您从segueUIButton连接的AnotherViewController

现在从包含segue的按钮添加ViewControllerAnotherViewController。 (不是从UIButtonAnotherViewController,而是从ViewControllerAnotherViewController)。并提供segue您期望的标识符。

相关问题