Search code examples
xcodeswiftsegueunwind-segue

Passing data from the second view into the first view controller


I want to know how do you pass data, like values, from a second view controller into the first view controller. I did a simple segue from the first to the second. I just don't know how to do it backwards.

I have a view on my first controller, and a view on the second one. I want to pass the changes from the second view into the view on the first controller when I click on a custom back button I made. How do I go about doing that?

I know it has something to do with unwind segue, but everything I look up is very unclear and confusing.


Solution

  • To do it backwards, you could do it with delegate or blocks like what @Rob linked in the comments.

    You can also do a unwind segue like what you mention. Just like a simple segue, unwind segue could help you pass data from the second view controller to first view controller in prepareForSegue.

    Example you have a ViewControllerA that segue to the ViewControllerB. This time you want to setup the unwind segue for ViewControllerB to ViewControllerA. Before setting up on storyboard, you will need to setup the @IBAction in ViewControllerA the UIViewController you want to unwind to not ViewControllerB. Something like this:

    @IBAction func cancelToViewControllerA(segue:UIStoryboardSegue) {
    }
    

    In storyboard, at the ViewControllerB control drag the button that will call the unwind segue to the exit and select cancelToViewControllerA. Then give it a name for the unwind segue. In ViewControllerB override prepareForSegue like what you did for passing data forward to set the data for the unwind segue.