如何使用TabBarViewController作为根创建导航堆栈?

时间:2016-02-15 02:29:22

标签: ios objective-c swift

我的TabBarVC是我的应用程序的核心。我有3个视图控制器。每个视图控制器都是"嵌入"在导航控制器中。

TabBarVC -> UINavigationController -> HomeVC
         -> UINavigationController -> TimelineVC
         -> UINavigationController -> ConversationVC

我希望我的TabBarVC能够随时将InstantMessageViewController推送到其堆栈中。据我所知,TabBarVC没有" stack"或者一个NavigationController - 只有它的孩子有导航控制器。

TabBarVC收到NSNotification时,我想将InstantMessageViewController推到其堆栈上。

TabBarVC内可能是这样的吗?

let mvc = self?.storyboard?.instantiateViewControllerWithIdentifier("MessagesViewController") as! InstantMessagesViewController
mvc.user = self?.notificationUser
self?.navigationController?.pushViewController(mvc, animated: true) //it doens't work because self.navigationController is nil.

当用户按下后退按钮时,它将返回TabBarVC。

我希望能够随时将多个InstantMessagesViewController推送到堆栈中并以编程方式重新排序。

我不知道什么是最好的方法。我是否创建了一个UIWIndow?我是否以编程方式创建UINavigationController?

1 个答案:

答案 0 :(得分:1)

您可以做的一件事就是将InstantMessagesViewController推送到UINavigationController上当前所选的UITabBarController

// Inside your UITabBarController
if let navigationController = selectedViewController {
    let mvc = self?.storyboard?.instantiateViewControllerWithIdentifier("MessagesViewController") as! InstantMessagesViewController
    mvc.user = self?.notificationUser
    navigationController.pushViewController(mvc, animated: true)
}

但正确的做法是以模态方式呈现InstantMessagesViewController(并将随后的InstantMessagesViewController推送到此UINavigationController堆栈上):

let mvc = self?.storyboard?.instantiateViewControllerWithIdentifier("MessagesViewController") as! InstantMessagesViewController
mvc.user = self?.notificationUser
let navController = UINavigationController(rootViewController: mvc)
presentViewController(navController, animated: true, completion: nil)

要在您的根UINavigationController上关闭此InstantMessagesViewController,请在InstantMessagesViewController内尝试以下代码:

override func viewDidLoad() {
    super.viewDidLoad()

    if let navigationController = navigationController {
        if navigationController.viewControllers.count == 1 {
            let barButton = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: "onBackTapped:")
            navigationItem.leftBarButtonItem = barButton
        }    
    }
}

func onBackTapped(barButtonItem: UIBarButtonItem) {
    dismissViewControllerAnimated(true, completion: nil)
}