How can I switch to some tab in UITabBarController
using StoryBoard? I have tried the code below but without success (the tab is not selected):
Alexander, I think your problem is getting correct instance of your tab bar. If your tab bar is your root view controller, then you can do it like this in your appdelegate if didFinishLoading method:
UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
[tabBar setSelectedIndex:3];
Give it a try and tell me the result please.
*Swift Comment - 18 months later if you convert Yanchi's solution into Swift in your appDelegate you'll get the expected result. The Swift translation is:
let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController
tabBar.selectedIndex = 1
This will work in stroryboard too...
[self.tabBarController setSelectedIndex:3];
with this add UITabBarControllerDelegate
in .h
and then use this delegate
method
- (BOOL)tabBarController:(UITabBarController *)theTabBarController shouldSelectViewController:(UIViewController *)viewController
{
return (theTabBarController.selectedViewController != viewController);
}
You can achieve this also using storyboards only. Ctrl-drag from the tabBarController to your ViewController(s), and select 'Relationship Segue, View controllers'. The first ViewController you select will be the default/initial ViewController.
I'm using IBInspected in LSwift
:
extension UITabBarController {
@IBInspectable var selected_index: Int {
get {
return selectedIndex
}
set(index) {
selectedIndex = index
}
}
}
You can also set the default tab in "User Defined Runtime Attributes" using storyboard.
Select your Tab Bar Controller from storyboard, in the right pane select Identity Inspector and add an attribute:
Key Path : selectedIndex Type : Number Value : 2 ( whatever number you want )