Search code examples
iosswiftuinavigationcontrollerrootviewcontroller

Correct way setting 'Root ViewController' thru 'UINavigationController' subclass


I'm trying to dynamically, using code change the Root of my UINavigationController thru his subclass.

Basically, my Storyboard looks like this:

#MARK : App Storyboard

enter image description here

As you can see, I set the the CustomNavigationController as the Initial View Controller option (thru the Storyboard).

How can I, thru the CustomNavigationController class, set up the root ViewController that will be displayed when i'll run the app?

#MARK : 'CustomNavigationController' class

class CustomNavigationController: UINavigationController {

  // What method should i use?

}

Solution

  • The two view controllers on the right must be given storyboard identifiers (on the identity inspector tab).

    Then in your custom NavVC, build the view controller you want at the root, and make it the root by making it the only view controller in the navigation stack (which is an array)...

    - (void)viewWillAppear:animated {
        [super viewWillAppear:animated];
        UIStoryboard *storyboard = [self storyboard];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"one of the ids you set up"];
        self.viewControllers = @[ vc ];
    }
    

    In swift (pretty sure)...

    override func viewWillAppear() {
        super.viewWillAppear()
        let storyboard = self.storyboard
        let vc = storyboard.instantiateViewController(withIdentifier: "one of the ids you set up")
        self.viewControllers = [ vc ] 
    }