Bhavik P. Bhavik P. - 2 years ago 232
Swift Question

navigationController is nil in swift

I have two storyboard (Main and SB2)

I have one view controller in storyboard in Main and one in SB2
I perform

let SB2 = UIStoryboard(name: "SB2", bundle:nil)
let vc : UIViewController = self.SB2.instantiateViewControllerWithIdentifier("VC2")
self.showViewController(vc, sender: self)

After the second viewcontroller loads and this command is run, it prints nil:

print(self.navigationController) // prints nil

In SB2 (second storyboard) I clicked on the viewcontroller (VC2) and then clicked on Editor > Embed In > Navigation Controller. This placed a navigation controller with the storyboard and the root view controller is VC2. I triple checked this. The first sign of it being connected was the gray navigation bar on top. The second being that there is segue connecting the navigation controller to VC2 and the last place I could have checked is in the navigation controller utilities.

I am thinking that maybe I shouldn't transition from VC1 to VC2 directly but rather VC1 to NavigationController however I don't know how to do this or if its even possible.

I don't know when sb2 prints nil when in face a navigation controller is connected to it. Any help is appreciated.

Answer Source

You need to push the view controller (VC2) on to the navigation controller.

let SB2 = UIStoryboard(name: "SB2", bundle:nil)v
let nvc = SB2.instantiateViewControllerWithIdentifier("NVC") as! UINavigationController
let vc : UIViewController = self.SB2.instantiateViewControllerWithIdentifier("VC2")
nvc.pushViewController(vc, animated: true)

Then try calling

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download