Search code examples
swiftuiviewcontrolleruinavigationcontroller

how to call existing navigationcontroller in Swift


I have 3 items in my storyboard. 1. viewController (A) connected to 2. Navigation controller and 3. viewController (B) is NOT connected to anything All 3 items have restoration identifiers set in the storyboard.

viewController (B) is the initial view controller. I am trying in B to get the navigation controller that A is attached to, but always returns nil:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyBoard.instantiateViewControllerWithIdentifier("viewControllerA") as! ViewControllerA
print(vc.navigationController?) // always prints nil

why!?

UPDATE#1 I can't declare a UINavigationController like a view controller. I've tried setting navigationcontroller with the id of 'myNavigationController' as storyboardID:

When storyboard, I get this error

let navigationController = storyBoard.instantiateViewControllerWithIdentifier("myNavigationController") as! UINavigationController
print(self.navigationController!) // fatal error: unexpectedly found nil while unwrapping an Optional value

I've also tried setting the id in restoration identifier, It bombed earlier at the instantiating line

@ColdLogic, see what hits I get when I search the entire project for that identifier:

enter image description here


Solution

  • Because you never instantiated the navigation controller, you instantiated view controller A. You would want something like this if you want both the nav controller and the view controller to be setup like they are in the storyboard

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let navigationController = storyBoard.instantiateViewControllerWithIdentifier("YourNavControllerIdentifier") as! UINavigationController
    let vc = navigationController.topViewController as! ViewControllerA
    

    Your code directly instantiates an object of type ViewControllerA. Which, unless you setup logic to do it, does not have a navigation controller by default.