问题
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):
self.tabBar.selectedIndex = 3;
Honestly I used nib files without StoryBoard and this code above worked fine in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions
:(NSDictionary *)launchOptions
but now I can't set the tab programatically. Maybe there is another problem that is not connected to selecting the tab. How can I switch tabs?
回答1:
Grab your instance of UITabBarController
then set the selectedViewController
property:
yourTabBarController.selectedViewController=[yourTabBarController.viewControllers objectAtIndex:3];//or whichever index you want
回答2:
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.
回答3:
*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
回答4:
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);
}
回答5:
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.
回答6:
I'm using IBInspected in LSwift
:
extension UITabBarController {
@IBInspectable var selected_index: Int {
get {
return selectedIndex
}
set(index) {
selectedIndex = index
}
}
}
回答7:
Swift 4.1
In your TabBarViewController
class, you can add this key line
self.selectedIndex = 0
回答8:
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 )
来源:https://stackoverflow.com/questions/17919302/how-do-i-set-selected-tab-in-uitabbarcontroller-using-storyboard