Swift: How to pass data when popping view controller

703 Views Asked by At

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?

3

There are 3 best solutions below

0
Eric Shieh On

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.

0
Louis Liang On

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
Mr.SwiftOak On

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

}