弹出到根控制器,但弹出到选项卡控制器上的特定选项卡

时间:2016-04-01 12:52:51

标签: ios swift

我有5个选项卡,当弹出到根控制器时,它会将我带到最后一个使用的选项卡。有没有办法可以跳转到特定标签?

 //takes me to last used tab on the tab controller
 @IBAction func goHome(sender: AnyObject)
{
 self.navigationController?.popToRootViewControllerAnimated(true)
}

例如,如果我打开10个视图控制器然后单击上面的按钮我想跳转到tabcontroller索引0这是主页

5 个答案:

答案 0 :(得分:2)

此代码将带您进入选项卡并弹出到那个标签的根视图控制器。

func buttonAction(sender: AnyObject){
    let someTabIndex = 0
    // Get the tabBar
    let t = self.tabBarController
    // Change the selected tab item to what you want
    t?.selectedIndex = someTabIndex
    // Pop the navigation controller of that index
    let v = t?.viewControllers?[someTabIndex]
    if let n = v?.navigationController {
        n.popToRootViewControllerAnimated(true)
    }

}

答案 1 :(得分:2)

func goToRootOfTab(index: Int) {
    let window = (UIApplication.shared.delegate as? AppDelegate)?.window
    let tabBar :UITabBarController? =  window?.rootViewController as? UITabBarController
    tabBar?.selectedIndex = index
    // pop to root if navigated before
    if let nav = tabBar?.viewControllers?[index] as? UINavigationController {
        nav.popToRootViewController(animated: true)
    }
}

答案 2 :(得分:0)

由于这是Swift,您可能需要检查您的标签栏控制器是否为祖先,以防您的应用结构发生变化:

@IBAction func goHome(sender: UIButton) {
    self.navigationController?.popToRootViewControllerAnimated(true)
    if let tab = self.tabBarController {
        tab.selectedIndex = 0  // Or whichever number you like
    }
}

答案 3 :(得分:0)

第一种情况:要选择其他标签索引

guard let VCS = self.navigationController?.viewControllers else {return }
for controller in VCS {
    if controller.isKind(of: TabBarController.self) {
        let tabVC = controller as! TabBarController
        tabVC.selectedIndex = index . (Select any index for tab)
        self.navigationController?.popToRootViewController(animated: true)
    }
}

第二种情况:当您要访问RootViewController变量

guard let VCS = self.navigationController?.viewControllers else {return }
for controller in VCS {
    if controller.isKind(of: TabBarController.self) {
        let tabVC = controller as! TabBarController
        //    tabVC.selectedIndex = 0 . //no need of this line if you want to access same tab where you have started your navigation
        let VCs = tabVC.selectedViewController as! MyViewController
        VCs.variableName = true . //access your variable
        self.navigationController?.popToRootViewController(animated: true)
    }
}

答案 4 :(得分:0)

首先获取对所选标签的引用,然后弹出到根目录。

if let tab = tabBarController  {
     tab.selectedIndex = 0
     if let navcon = tab.selectedViewController as? UINavigationController {
                        navcon.popToRootViewController(animated: true)
     }

}