我将数据从一个VC传递回第一个VC。我使用此代码:
@IBAction func goBack(_ sender: Any) {
dismiss(animated: true, completion: nil)
print(self.entryField.text!)
performSegue(withIdentifier: "sendText", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destVC = segue.destination as! ViewController
let printName = self.entryField.text!
print(self.entryField.text!)
destVC.nameToDisplay=printName
}
这是我的VC代码,其中包含数据。
我要在其中显示结果的VC代码。
var nameToDisplay = ""
override func viewWillAppear(_ animated: Bool) {
titleDisplay.text=nameToDisplay
}
我无法传递数据,我尝试打印nameToDisplay
,但它会显示空字符串。
答案 0 :(得分:0)
将值从第二个控制器传递回第一个控制器的合理模式可能是这样的:
class FirstViewController: UIViewController {
//......
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let secondViewController = segue.destination as? SecondViewController {
secondViewController.nameHandler = { (name) -> Void in
titleDisplay.text=nameToDisplay //second controller will call back here to pass the name value when it's going back.
}
}
}
//......
}
class SecondViewController: UIViewController {
//......
var nameHandler:((_ name:String)->Void)? //a closure to call back name
@IBAction func goBack(_ sender: Any) {
if let name = self.entryField.text {
self.nameHandler?(name) //call back and pass the name to the first controller
}
dismiss(animated: true, completion: nil)
}
//......
}
答案 1 :(得分:0)
您正在寻找viewcontrollers之间的一对一通信。这可以通过iOS中的不同方式实现。
1-代表团
2块,关闭。
以上解决方案是使用块。我会告诉你代表们
class FirstVC: UIViewController, PassData {
func pushVC() {
let secondVC = SecondVC()
secondVC.delegate = self
self.navigationController?.pushViewController(secondVC, animated: true)
}
func passDataOnDismiss(data: String) {
print(data)
}}
protocol PassData: class {
func passDataOnDismiss(data: String)
}
class SecondVC: UIViewController {
weak var delegate: PassData?
@IBAction func didButtonPress() {
self.delegate?.passDataOnDismiss(data: "I am passing this string back to First VC")
self.navigationController?.popViewController(animated: true)
}
}