nyanev
nyanev

Reputation: 11519

iOS change tab programmatically

I'm developing an iOS application with a tab bar and navigation. When I press a button in the first tab I want it to load the second tab with a navigation controller and push the next view. Can someone help with this?

Upvotes: 1

Views: 3273

Answers (4)

zic10
zic10

Reputation: 2330

Here is a Swift solution for anyone that needs it. I had to do the same thing just go from a nested view controller in tab 2 to another nested view controller in tab 4. Here is how I achieved that:

func goToHelpViewController(){
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        let desiredIndex:Int = 3
        self.tabBarController?.selectedIndex = desiredIndex
        let settingsStoryBoard = UIStoryboard(name: "SettingsSection", bundle: nil)
        let helpViewController = settingsStoryBoard.instantiateViewControllerWithIdentifier("HelpViewController") as! HelpViewController
        let settingsRootNavigationController = self.tabBarController?.viewControllers![desiredIndex] as! UINavigationController

        settingsRootNavigationController.popToRootViewControllerAnimated(false)
        settingsRootNavigationController.pushViewController(helpViewController, animated: true)
    })
}

Swift 3.0

func goToHelpViewController(){
    DispatchQueue.main.async(execute: { () -> Void in
        let desiredIndex:Int = 1
        self.tabBarController?.selectedIndex = desiredIndex
        let settingsStoryBoard = UIStoryboard(name: "SettingsSection", bundle: nil)
        let helpViewController = settingsStoryBoard.instantiateViewController(withIdentifier: "HelpViewController") as! HelpViewController
        let settingsRootNavigationController = self.tabBarController?.viewControllers![desiredIndex] as! UINavigationController

        settingsRootNavigationController.popToRootViewController(animated: false)
        settingsRootNavigationController.pushViewController(helpViewController, animated: true)
    })
}

Upvotes: 1

David Hoerl
David Hoerl

Reputation: 41642

The button in the first tab sends a message to the tab controller, telling it to select the second tab. Then you send a message to the rootView of the second tab, which is a navigation controller, and tell it to push such and such an object that you create in the class with the first button.

Upvotes: 1

Pandey_Laxman
Pandey_Laxman

Reputation: 3908

You can programatically select tab by

self.tabBarController.selectedIndex=1;

Upvotes: 2

Manish Agrawal
Manish Agrawal

Reputation: 11026

Set selectedViewController:

self.tabBarController.selectedViewController = viewControllerYouWant;

For example,

self.tabBarController.selectedViewController 
    = [self.tabBarController.viewControllers objectAtIndex:2];

Upvotes: 1

Related Questions