-1

I'm passing the data from one VC back to the first VC. I'm using this code:

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

This is my code of the VC in which the data is.

The code of the VC in which I want to display my result.

var nameToDisplay = ""

override func viewWillAppear(_ animated: Bool) {
    titleDisplay.text=nameToDisplay
}

I'm unable to pass the data, I tried printing the nameToDisplay but it gives empty string.

2 Answers2

0

A reasonable pattern for passing back the value from second controller to the first one could be like this:

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

    //......
}
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33
0

You are looking for one to one communication between viewcontrollers. This can be achieved by different ways in iOS.

1- Delegation

2- blocks, closures.

The above solution is using block. I will tell you with delegates

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)
    }
}
Scriptable
  • 19,402
  • 5
  • 56
  • 72
Mridul Gupta
  • 599
  • 5
  • 18