Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Present a view controller, dismiss it and present a different one in Swift

I have a root view controller that has a button that when the user pushes it, another view controller is presented.

This second controller has a dismiss option that just comes back to the root view controller and a button that when the user touches it dismisses the current view controller so it goes back to the root view controller for a second and presents another one.

Going to the first controller I use:

let vc = FirstController() self.present(vc, animated: true, completion: nil) 

And when in the other view controller I select the button that only dismisses I do this.

self.dismiss(animated: true, completion: nil) 

So for the second controller that needs to dismiss and present another one I have tried the following:

self.dismiss(animated: true, completion: {     let vc = SecondController()     self.present(vc, animated: true, completion: nil) }) 

But I get an error:

Warning: Attempt to present <UINavigationController: 0xa40c790> on <IIViewDeckController: 0xa843000> whose view is not in the window hierarchy!

like image 360
ravelinx Avatar asked Apr 23 '17 01:04

ravelinx


People also ask

How do you dismiss the presenting view controller?

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it.

How do I present a two view controller in Swift?

For solving this, you will need to do a pretty simple trick which is to take a screenshot from the first view controller and passing it to the second view controller to display it while presenting the third view controller. You can check this repository to see how it is exactly could be done (Swift 3).


1 Answers

The error occurs because you are trying to present SecondController from FirstController after you have dismissed FirstController. This doesn't work:

self.dismiss(animated: true, completion: {     let vc = SecondController()      // 'self' refers to FirstController, but you have just dismissed     //  FirstController! It's no longer in the view hierarchy!     self.present(vc, animated: true, completion: nil) }) 

This problem is very similar to a question I answered yesterday.

Modified for your scenario, I would suggest this:

weak var pvc = self.presentingViewController  self.dismiss(animated: true, completion: {     let vc = SecondController()     pvc?.present(vc, animated: true, completion: nil) }) 
like image 163
Mike Taverne Avatar answered Nov 06 '22 02:11

Mike Taverne