Search code examples
iostabbar

How to know which Tabbar Menu Clicked


I have an UITabBarController which is linked to 5 viewcontrollers as shown in the figure bellow.

In my opening screen, I have register page, if user does not register then I do not want to allow user to see any content of Rewards and Offers ViewController.

Whenever user clicks on tabbarviewcontroller, I would like to generate an UIAlertView that displays either register or cancel.

My question is when the user clicks on the Rewards or Offers, how should I know which tabbar menu clicked to generate UIAlertView ?

I am using storyboard. I have a tabbarcontroller and a custom class of this tabbarcontroller. Header file is as follows:

#import <UIKit/UIKit.h>

@interface MainHarvestGrillTabBarViewController : UITabBarController <UITabBarDelegate>

@end

I would like to know how should I have access which tab is clicked.

I have implemented the following code, but it always return o no matter which tab is clicked.

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSUInteger index = self.tabBarController.selectedIndex;
    NSLog(@"index %lu",(unsigned long)index);
    // Recenter the slider (this application does not accumulate multiple filters)
    // Redraw the view with the new settings
}

enter image description here


Solution

  • You could check which tab was selected using the tab bar's didSelectItem protocol method but this won't prevent the view controller from being displayed. Instead you can make use of the UITabBarControllerDelegate protocol and implement the shouldSelectViewController:(UIViewController *)viewController method. So then you would check the selected view controller and act accordingly. Below is an example for preventing the user selecting the Rewards tab:

    - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
        if ([tabBarController.viewControllers objectAtIndex:3] == viewController) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Alert message" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alertView show];
            return NO;
    
        }
        return YES;
    }
    

    You'd place this in your tab bar controller class. You also need to add <UITabBarControllerDelegate> to your header file and set self.delegate = self; in viewDidLoad.