Search code examples
swiftuinavigationcontrollermodal-dialog

Present modal while transitioning to the previous view


When I leave a particular view controller, I want to have it display a modal view over the previous view in the navigation stack. Currently I'm doing it with this code:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationController?.viewControllers.last?.present(myModalView, animated: false, completion: nil)
}

This seems to work, but every time I leave the view I get a warning in the console:

Presenting view controllers on detached view controllers is discouraged <Project.MyViewController: 0x7fe09281a400>.

So I'm concerned that there might be a problem I haven't run into yet. Is there a "correct" way of doing this?


Solution

  • As it turns out, self.present(myModalView, animated: false, completion: nil) works perfectly with no warnings. In retrospect, I probably should have tested that first, but I had assumed it wouldn't work since the view was disappearing.

    Additionally, it does not work at all with animated: true, whereas my original solution does with no warnings (but I don't want it to be animated). Not sure if that's just how the asynchronous processes work out or if there's something more to it.