Chris
Chris

Reputation: 282

Dismissing Modally Presented VC and Popping Presenting VC

I have a viewcontroller embedded in a navigationcontroller that pushes another viewcontroller onto the stack. This pushed viewcontroller has an embedded viewcontroller that segues/modally presents a final viewcontroller.

On a button click, I am trying to dismiss the final presented viewcontroller and pop the present-ing viewcontroller and return to the initial state.

Thus far, I've been able to get the dismiss going, but popping does not seem to work in the completion handler of the dismiss.

I've tried printing out the hierarchy, i.e. self.presentingViewController, self.navigationController, self.presentingViewController.presentingViewController..., all of which output nil, and am admittedly stuck now on returning to the initial state.

In looking at the view hierarchy, the final presented viewcontroller is beneath a UITransitionView separate from the rest of the stack I had mentioned earlier..

Any thoughts/guidance would be appreciated.

Upvotes: 0

Views: 316

Answers (2)

jjrscott
jjrscott

Reputation: 1542

Since you mentioned segues I think unwind segues might help. I built a quick test project and they do indeed function correctly in your scenario.

There is a rather excellent answer in a related SO question What are Unwind segues for and how do you use them?. A summary of the answer for your particular case is: place the following function in your initial view controller:

@IBAction func unwindToThisViewController(segue: UIStoryboardSegue)
{
}

You can then directly 'unwind' to that viewcontroller by using Storyboard Segues directly (as in the referenced answer) or programatically via:

self.performSegue(withIdentifier: "unwindToThisViewController", sender: self)

Again there's a good article entitled Working with Unwind Segues Programmatically in Swift which goes into lots of detail.

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

Can you try

if let nav = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {

     self.dismiss(animated:true) {

        nav.popToRootViewController(animated:true)
     }
 }

Upvotes: 0

Related Questions