Reputation: 16793
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
}
Upvotes: 0
Views: 295
Reputation: 6039
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
.
Upvotes: 1
Reputation: 13549
To grab the index of the selected tab item:
NSUInteger index = self.tabBarController.selectedIndex;//The index of the view controller associated with the currently selected tab item.
Or if you would like to grab the actual viewController associated with the selection you could do this:
id yourViewController = [self.tabBarController selectedViewController];//The view controller associated with the currently selected tab item
Upvotes: 1