Search code examples
swiftmodal-dialogsegueviewcontrollerlifecycle

Swift - Segue away from modal view not destroying ViewController properly


I'm having trouble figuring out how to properly destroy ViewControllers. In my project, I have 3 view controllers. The Storyboard Layout (IMG)

The first view controller segues to the second view controller. The second view controller segues modally to the third view. When the third view is on the screen, the second screen can still be seen in the background (the third view has a transparent background).

However, when I segue away from the third view controller and back to the first view controller, the second view controller that is in the background is not destroyed. I logged the view controller lifecycle events to illustrate what I mean:

viewDidAppear - ViewController1
viewWillDisappear - ViewController1
viewDidAppear - ViewController2
viewDidAppear - ViewController3
viewWillDisappear - ViewController3
viewDidAppear - ViewController1

As you can see from the above console print statements, ViewController2 is never being destroyed anywhere. Logically, I assumed that it would be destroyed along with ViewController3 when VC3 segued back to VC1. However, this is not the case, most likely due to the intricacies of how modal views work in Swift.

How can I fix this? I need VC2 to call viewWillDisappear


Solution

  • Credit to vacawama for pointing out the solution.

    I ended up implementing an unwind segue when I needed to go back from ViewController3 to ViewController1. I did this programatically, following the steps shown in this tutorial:

    https://www.andrewcbancroft.com/2015/12/18/working-with-unwind-segues-programmatically-in-swift/