当您使用setSelectedViewController
时,控制器必须是标签栏控制器viewControllers
数组中的一个。但是你在这里创建了一个新的控制器,所以它必然会失败。你应该只使用setSelectedIndex
. 这是最简单的。
因此,如果您使用的是 NIB,则didFinishLaunchingWithOptions
可能如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[viewController1, viewController2];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
// tell the tab bar controller to start with the second tab
[self.tabBarController setSelectedIndex:1];
return YES;
}
如果使用故事板,并且您的初始控制器是该选项卡栏控制器,您可以:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
[tabController setSelectedIndex:1];
return YES;
}