How can I show ViewController in UITabBarController?

徘徊边缘 提交于 2019-12-04 15:30:51

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

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

  • ViewControllerA
  • ViewControllerB

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

  • UINavigationController -> ViewControllerA
  • UINavigationController -> ViewControllerB

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)

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

Your root view controller is of type UITabBarController. Therefore you have to use the appropriate methods of this class and not UINavigationController. To set view controllers use either

var viewControllers: [UIViewController]? or

func setViewControllers([UIViewController]?, animated: Bool).

To have a navigation bar you have to instantiate a UINavigationController and add your view controller to this navigation controller. Then add your navigation controller to your UITabBarController with via one of the above options.

If your class is UITabBarController You can add this:

private func showViewController() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let vc = storyboard.instantiateViewController(withIdentifier: "queueTableViewController") as? QueueTableViewController else { return }
    let navVC = self.selectedViewController as? UINavigationController
    navVC?.pushViewController(vc, animated: true)
}

This will allow you to go to any VC

The second solution is something like this. Here You will show the last VC and from there push some VC.

    guard let tabCount = viewControllers?.count, tabCount > 1 else { return }
    selectedIndex = tabCount - 1
    if let navigationController = viewControllers?[selectedIndex] as? UINavigationController {
        if let accountVC = navigationController.visibleViewController as? FirstViewController {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            guard let vc = storyboard.instantiateViewController(withIdentifier: "someViewController") as? SomeViewController else { return }
            accountVC.navigationController?.pushViewController(vc, animated: true)
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!