iPhone: how to select a UITabBarItem programmatically

I’m working to an iPhone application with a TabBar on the footer area. Among the others there are a “Home” button and an “Account” button. The first allows the user to see a view that gives an overview of the application. The latter shows the view that the user uses to manage his/her account.

If the user is not currently logged in, in the “Home” view a warning message is displayed. There is also a button that is supposed to show the “Account” view. In that way it’s more clear for the user that he/she should log in.

How can you accomplish that task ? That post shows you the way I followed.

The big idea is to retrieve the TabBarController from the “Home” controller, and programmatically change the current view. To do that, the “Home” controller should get a reference to the TabBarController. But you can easily set that dependency in Interface Builder. You only need to provide a suited IBOutlet to the Home controller.

That is the tree structure of the controllers and views, as built in the interface builder.


So, that’s an excerpt of the HomeController showing you only what is really needed to reach our goal. The goToRegistrationPage method will execute programmatically the switch to the account page.

@interface HomeViewController : UIViewController {
UITabBarController *mainTabBarController;
@property(nonatomic, retain) IBOutlet UITabBarController *mainTabBarController;
-(IBAction) goToRegistrationPage;

Now, we only need to set in Interface Builder the link between the the IBOutlet we just created and the Tab Bar Controller. Here’s the result.

iphone_change_tabbar_programmatically_1As you can see the mainTabBarController outlet is linked to the Tab Bar Controller we want to manage programmatically. That’s not difficult at all. Let’s give a look to the goToRegistrationPage method.

-(IBAction) goToRegistrationPage {

Quite easy, isn’t it ?

Now the user click on the button on the Home view and he/she get exactly the same result of touching the tab bar button in the footer.

Hope you can find it useful.