-1

I want to pass data from childVC to parentVC when popping view controller.

ChildViewController { /processing data/ //get data value
value = 123 self.navigationController?.popViewController(animated: true) }

ParentViewController { //use the value from child vc(value 123) }

How can i pass the data back to use it in ParentViewController?

IskandarH
  • 99
  • 1
  • 13
  • 1
    you can use a segue https://stackoverflow.com/a/35314768/2303865, post a notification https://stackoverflow.com/a/30541063/2303865 or use a delegate https://stackoverflow.com/a/60840590/2303865 – Leo Dabus Jun 25 '21 at 02:42

3 Answers3

1

You can use a segue, and prepare for the segue before popping to the new view controller.

In VC1

performSegue(withIdentifier: "toVC2", sender: self)

let dataInVC1 = "wow"

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toVC2" {
        let vc = segue.destination as SecondViewController
         vc?.someData = dataInVC1
}

In VC2

var someData: String?
0

Easiest way is to use a callback closure property on the child. Set it from the parent when setting up the child view controller. When the child is done, check if callback is != nil (if optional) and if so, call it before popping.

Eric Shieh
  • 697
  • 5
  • 11
0

You can also create your custom handler for completion after you pop. Here is an example:

extension UINavigationController {

func popViewControllerWithHandler(animated:Bool = true, completion: @escaping ()->()) {
    CATransaction.begin()
    CATransaction.setCompletionBlock(completion)
    self.popViewController(animated: animated)
    CATransaction.commit()
}

}

Mr.SwiftOak
  • 1,469
  • 3
  • 8
  • 19