1

I am trying to change tab programmatically in storyboard but getting error

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

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

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

Error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

Here tabBarCon.viewControllers is not empty.

NSLog(@"%@",tabBarCon.viewControllers); giving

(
"<FirstViewController: 0x16642020>",
"<SecondViewController: 0x173c4c00>",
"<ThirdViewController: 0x166db570>",
"<ForthViewController: 0x166d17c0>",
"<FifthViewController: 0x166066a0>"
)
3
  • log shows the crash occurs while inserting nil object to the array. try adding exception breakpoint to detect the exact line that cause crash. Apr 7, 2016 at 11:17
  • line tabBarCon.selectedViewController = [tabBarCon.viewControllers objectAtIndex:1]; is crashing Apr 7, 2016 at 11:19
  • just say tabBarCon.selectedIndex=1; Apr 7, 2016 at 11:29

3 Answers 3

2

You need to have instance of tabbarcontroller.

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

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

This statement creates new instance of tabbar from storyboard.

[self.tabBarController setSelectedIndex:1];

If you are within the tab bar controller then you will easily get the instance using self.tabBarController

0

Try This:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
TabViewController *tabBarCon = [storyboard                            instantiateViewControllerWithIdentifier:@"tabBar"];
[self.tabBarController setSelectedIndex:1];
1
  • Have you try to set selectedIndex after pushing or presenting tabbarcontoller ....... Apr 7, 2016 at 12:26
0

Try This

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

i have tried on Appdelegate it is working

4
  • i have put that code on Appdelegate so there is self.window.rootViewController sorry for that Apr 7, 2016 at 11:41
  • Second line incomplete Apr 7, 2016 at 12:19
  • mean [controller setSelectedIndex:1] ? @Salim Apr 7, 2016 at 12:21
  • you can also set [self setSelectedIndex:1] to sub class of your UITabbarController Also working Apr 7, 2016 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.