Search code examples
swiftvariablessegueviewcontroller

Pass variable to other view controller via back button


I have two view controllers. One is navigated to with a "show" segue. There is a back button in the UINavigationBar that I have not changed. The back button goes back to the initial view controller. In the view controller with the back button, I am storing data in a variable.

How can I pass this data to my initial view controller?

I have tried:

viewWillDisappear(_ animated: Bool) {
    let vc = ViewController()
    vc.data = items
}

but the data in the initial view controller is empty when printed.

I've attempted to use:

prepare(for segue: ...)

but I'm not sure what segue the back button uses.

I can't seem to add an action of the back button to my view controller either.


Solution

  • You could use a delegate. First, create a protocol:

    protocol getItemsDelegate {
        func getItems(_ items: [String])
    }
    

    In your first view controller's class definition add getItemsDelegate:

    class myFirstViewController: UIViewController,getItemsDelegate
    

    Add this to the prepare method in your first view controller:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! mySecondViewController
        vc.delegate = self
    }
    

    Lastly, in your first view controller, add this:

    func getItems(_ items: [String]) {
        // Do something with items
    }
    

    In your second view controller, declare the following property:

    var delegate: getItemsDelegate?
    

    Then:

    override func viewWillDisappear(_ animated: Bool) {
       delegate?.getItems(items)
    }
    

    This is just another way to do it.