Search code examples
uibuttonswift4uistoryboardseguexcode9unwind-segue

How connect a UIButton to the UIViewController Exit with code Swift


Lets say I have two UIViewControllers, we'll call them VC1 and VC2. VC1 performs a segue that then goes to VC2, and VC2 has a close button that will unwind that segue back to VC1.

So normally, if I'm wanting to make a custom UIStoryboardSegue I would make a segue from VC1 to VC2 and then select custom and use my custom UIStoryboardSegue I made that and I have it working just fine.

And for the close button I would put in code in the destination UIViewController (VC1) like this:

@IBAction func prepareForUnwind(unwindSegue: UIStoryboardSegue) {
    //some code
}

Then on the UIViewController with the close button, I would ctr + drag up to the EXIT and select that unwind prepareForUnwind. Then I'd select the UnwindSegue on the left panel and change the class to my unwind class.

The problem is, in my case I am having to create that button with code, so I don't have the option of ctr + drag. So how do I connect it to the exit and then assign the class for the unwind segue with code only? I've tried googling it, but everything keeps coming back with the method when you are using the storyboard.

I can include more code if necessary, just let me know.


Solution

  • You can connect your button in this way:

    First Step

    In the Storyboard connect with drag and drop your source view controller name icon with the exit icon, there you should see in the pop-up your prepareForUnwind function.

    Then you can set for your unwind segue an identifier.

    Second step

    Add an @IBAction function for your close button and perform the segue:

    @IBAction func closeAction() {
        performSegue(withIdentifier: "yourExitIdentifier", sender: self)
    }