如何在 UITabBarController 中显示 ViewController?

How can I show ViewController in UITabBarController?

我有一个 UITabBarController,我的所有其他视图控制器都连接到它。现在我想将我的控制器显示为:

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

但是当我尝试:

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

它给了我下一个错误:

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

后来我试过:

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

但在这种情况下我得到

UITabBar has no member pushViewController

我怎样才能 show/push 我的 ViewController 它会出现在 UINavigationBar 和 UITabBar 内部?

您需要将每个视图控制器放在导航控制器中。

例如目前你有一个 TabBarViewController 和两个视图控制器:

  • ViewControllerA
  • ViewControllerB

您需要做的是将它们中的每一个嵌入到导航控制器中,这样您就可以:

  • UINavigationController -> ViewControllerA
  • UINavigationController -> ViewControllerB

为了推送一个新的控制器,你会这样做:

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'

您的根视图控制器属于 UITabBarController 类型。 因此,您必须使用此 class 的适当方法,而不是 UINavigationController。 要设置视图控制器,请使用

var viewControllers: [UIViewController]?

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

要拥有导航栏,您必须实例化 UINavigationController 并将您的视图控制器添加到此导航控制器。 然后通过上述选项之一将导航控制器添加到 UITabBarController。

如果你的 class 是 UITabBarController 您可以添加:

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)
}

这将允许您前往任何 VC

第二种解决方案是这样的。 在这里您将显示最后一个 VC 并从那里推送一些 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)
        }
    }