iosswiftstoryboarduitabbarcontrollerpushviewcontroller

How can I show ViewController in UITabBarController?


I have a UITabBarController and all my other view controllers are connected to it. Now I want to show one my controller as:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc: ViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController

but when I tried to:

let rootViewController = self.window?.rootViewController as! UINavigationController
rootViewController.pushViewController(vc, animated: true)

it gave me the next error:

Could not cast value of type 'UITabBarController' (0x1a899b818) to 'UINavigationController'

Later I've tried to do:

let rootViewController = self.window?.rootViewController as! UITabBarController

but in this case I get

UITabBar has no member pushViewController

How can I show/push my ViewController so it will appear with UINavigationBar and inside of UITabBar?


Solution

  • You need to place each of your view controllers inside a navigation controller.

    E.g. currently you have a TabBarViewController and two view controllers:

    What you need to do is to embed each of them inside a navigation controller so you would have:

    In order to push a new controller you would do:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc: ViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
    
    let navViewController = myTabBar.selectedViewController as? UINavigationController
    navViewController?.pushViewController(vc, animated: true)