1

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

Necto
  • 2,594
  • 1
  • 20
  • 45

2 Answers2

0

I afraid you misunderstood segue. By segue from ViewController3 to ViewController1 you are just creating another instance of ViewController1 that stack above ViewController3. You are not going back.

You should be using a UINavigationController that hold a rootViewController to your ViewController1. The segue push a ViewController2 and the button that modal a segue to ViewController3.

On ViewController3 you need to dismiss it programatically in code using dismissViewControllerAnimated(true) then perform a navigationController?.popViewControllerAnimated(true) to go back to ViewController1

Zac Kwan
  • 5,587
  • 4
  • 20
  • 27
0

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/