Home > Software design >  NavigationController becomes nil after present a modal
NavigationController becomes nil after present a modal

Time:03-02

In my project, I'm using a modal to show a detail of a service with a button to confirm a navigation to this service. In all my screens, I have the following example code to navigate throug screens:

code #1

self.navigationController?.setViewControllers([servicesVC], animated: false)

or

code #2

self.navigationController?.pushViewController(servicesVC, animated: false)

and everything runs fine.

Then I present my CustomViewController as a modal using the following code:

self.navigationController?.present(serviceDetailVC, animated: true, completion: nil)

But if I try to navigate to another screen from my modal (serviceDetailVC) using the code #1 or #2, my navigationController becomes nil and I can do nothing.

What I'm doing wrong?

CodePudding user response:

use

self.present(serviceDetailVC, animated: true, completion: nil)

instead of

self.navigationController?.present(serviceDetailVC, animated: true, completion: nil)

CodePudding user response:

You're presenting modally ViewController that is not embedded in UINavigationController.

Instead of:

navigationController?.present(serviceDetailVC, animated: true)

You should do something like this:

let detailNC = UINavigationController(rootViewController: serviceDetailVC)
navigationController?.present(detailNC, animated: true)

This way, you'll be able to push/set other view controllers to your modal screen.

  • Related