Responding to the iPhone’s UITabBarController touches should be a direct, uncomplicated process, but in fact requires you to establish a number of hooks throughout your code. There are many reasons you might wish to intercept a UITabBar action, either to cancel and return to a prior tab, to show an alert view, to conditionally push a stack of ViewControllers , and so forth. Here are the steps necessary to make that happen.
(1) Add a UITabBarController property to your App Delegate’s class so you can access it through Interface Builder.
@interface MyAppDelegate : NSObject <UIApplicationDelegate>
{
UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
(2) Use Interface Builder to associate the tabbar control with the app delegate’s tabBarController property.
(3) Add the necessary delegate methods to your app delegate. UITabBarControllerDelegate is required, but if you want to use a UIAlertView as in this example, you’ll also need to add UIAlertViewDelegate as well.
@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate, UIAlertViewDelegate>
(4) Override the tabBarController’s didSelectViewController method. You can use the tabbar’s selectedIndex property to determine which tab was touched; in this example, an alert view confirms whether or not the user wants to quit the app.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
NSLog(@”User selected %@ from the tabbar”,viewController);
if (tabBarController.selectedIndex == 3){
UIAlertView *actionAlert = [[UIAlertView alloc]
initWithTitle:@”Quit Application”
message:@”Are you sure you want to quit the application?”
delegate:self cancelButtonTitle:nil
otherButtonTitles:@”Quit”, @”Resume”, nil];
[actionAlert show];
}
}
(5) Finally, respond to the alert view depending on the user’s selection.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) { // Quit
[self performSelector:@selector(saveAppAndExit:) withObject:nil afterDelay:.1];
}
else if (buttonIndex == 1) { // Resume
tabBarController.selectedIndex = 0; // Default tab
}
[alertView release];
}
There you have it; like many such tasks on the iPhone, it’s a simple problem otherwise obscured by the platform’s particular idioms. Note, there is one caveat: by the time you gain programmatic access to the UITabBarController via didSelectViewController, the selection has already occurred such that you can’t intercept the action, only respond to it.
