iOS:以编程方式更改标签 - 故事板

时间:2016-04-07 11:13:35

标签: ios objective-c uitabbarcontroller

我正在尝试在故事板中以编程方式更改标签但是收到错误

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

TabViewController *tabBarCon = [storyboard 
                            instantiateViewControllerWithIdentifier:@"tabBar"];

tabBarCon.selectedViewController = [tabBarCon.viewControllers objectAtIndex:1];

错误

由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' *** - [__ NSArrayM insertObject:atIndex:]:对象不能为零

此处tabBarCon.viewControllers不为空。

NSLog(@"%@",tabBarCon.viewControllers);给予

(
"<FirstViewController: 0x16642020>",
"<SecondViewController: 0x173c4c00>",
"<ThirdViewController: 0x166db570>",
"<ForthViewController: 0x166d17c0>",
"<FifthViewController: 0x166066a0>"
)

3 个答案:

答案 0 :(得分:2)

你需要有tabbarcontroller的实例。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

TabViewController *tabBarCon = [storyboard instantiateViewControllerWithIdentifier:@"tabBar"];

此语句从故事板创建tabbar的新实例。

[self.tabBarController setSelectedIndex:1];

如果您位于标签栏控制器内,那么您可以使用self.tabBarController

轻松获取实例

答案 1 :(得分:0)

试试这个:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
TabViewController *tabBarCon = [storyboard                            instantiateViewControllerWithIdentifier:@"tabBar"];
[self.tabBarController setSelectedIndex:1];

答案 2 :(得分:0)

试试这个

UITabBarController *controller =(UITabBarController *)     
self.window.rootViewController;
[controller setSelectedIndex:1];

我试过Appdelegate它正在运作