Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pop to root controller but to specific tab on the tab controller

Tags:

ios

swift

I have 5 tabs and when popping to the root controller it takes me to the last used tab. Is there a way I can jump to a specific tab?

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

for example, If I have 10 view controllers open and then click on the button above I want to jump to tabcontroller index 0 which is the home page

like image 571
swiftTonio Avatar asked Oct 29 '25 19:10

swiftTonio


2 Answers

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)
    }
}
like image 96
Bassant Ashraf Avatar answered Nov 01 '25 09:11

Bassant Ashraf


This code will take you to the tab and pop to the root view controller for that tab.

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

}
like image 25
ryantxr Avatar answered Nov 01 '25 08:11

ryantxr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!