Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
Bhavik P. Avatar asked Apr 19 '16 23:04

Bhavik P.


2 Answers

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 in your view controller try calling

self.navigationController
like image 149
InnisBrendan Avatar answered Sep 20 '22 10:09

InnisBrendan


In your storyboard, select the initial ViewController. With this view controller selected, choose the menu item

Editor -> Embed In -> Navigation Controller
like image 38
Shubham Goel Avatar answered Sep 21 '22 10:09

Shubham Goel