Search code examples
iosswiftsegueunwind-segue

SWIFT, ViewControllers and unwind segue to initial ViewController


I'm having trouble with Unwind Segue. I have 3 ViewControllers and they all under the class called ViewController.swift. I'm trying to get the last ViewController which is the 3rd to to go the beginning ViewController with just a tap of a button but I can't seem to get it. I tried to research before submitting this question but couldn't find it. If there is more information you need let me know.


Solution

  • You have VC1 -> VC2 -> VC3 and want to unwind from VC3 directly to VC1. In order to do this, you need an @IBAction defined in VC1 that isn't defined in VC2. That is currently not possible since all of your ViewControllers are using the same class definition in ViewController.swift.

    One way to resolve this without duplicating all of the code in ViewController.swift is to subclass ViewController and add just the function that is unique to VC1. Then in the Storyboard, select the first ViewController and in the Identity Inspector set the Custom Class to MainViewController.

    class MainViewController: ViewController {
        @IBAction func returnToMain(segue: UIStoryboardSegue) {
            print("back in the MainViewController")
        }
    }
    

    Then, when you set up your unwind segue, control-drag from your button to the Exit icon at the top of your 3rd ViewController and select the returnToMain action from the pop-up.