Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically changing the selected tab of tabBarController

I have a basic project created in xcode as a "Tab Bar Application", What I would like is to have the application on load switch to the 2nd tab if BOOL x is true.

Right now I have: (located in FirstViewController.m in viewDidLoad)

if(x){     [self.tabBarController setSelectedIndex:1]; } 

This causes the selected tab at the bottom of the page to highlight the 2nd tab, however the view remains that of the first tab.

How would I go about changing the view to that of the 2nd tab?

like image 484
Mike Valstar Avatar asked Jan 20 '11 16:01

Mike Valstar


1 Answers

Well, I reproduced your issue, and solved it by moving the switching logic from -viewDidLoad to -viewDidAppear:. So basically, change:

- (void)viewDidLoad {     // Other code...     if(x){         [self.tabBarController setSelectedIndex:1];     } } 

to:

- (void)viewDidAppear:(BOOL)animated {     // Other code...     if(x){         [self.tabBarController setSelectedIndex:1];     } } 

Now, as to why this is the case, I can only guess, without more digging, that it has to do with the order things are initialized. It is possible that your view controller's viewDidLoad is being called before the parent tab bar controller has finished its own initialization. Holding off until your view has actually appeared ensures that everything is loaded and in a consistent state.

like image 169
Matt Wilding Avatar answered Oct 05 '22 05:10

Matt Wilding