0

I have a tabBar that is implemented programmatically. I would like to be able to track if the user press a certain tabBar item (or button or whatever it's called). As far as I understand, this is done by inheriting from the UITabBarControllerDelegate class.

If I implement the UITabBarControllerDelegate code in one of the classes that the tabBar items navigates to, the didSelectViewController method works:

@interface ExperiencesContainerViewController () <ContainerProtocol, UITabBarControllerDelegate>
@implementation ExperiencesContainerViewController

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    NSLog(@"PRESS");
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tabBarController.delegate = self;

}

Now this works, but it works a bit too well as it triggers not only when I press the item of this particular class but whichever item I happen to press, even though those items navigate to a completely different class.

I would like the method to trigger only when I press the tabBar item of this particular class. And then I guess I would replicate this pattern in the other classes as well and have those methods trigger only when their respective tabBar item is pressed.

I read this:

Detect when a tab bar item is pressed

And the answer suggests that I should implement the UITabBarControllerDelegate in the class that handles the setup of the tabBar. I tried that but then the method isn't triggered. I think this has to do with the delegate suddenly being set to a class that is not associated with one of the tabBar items.

Let me know if there is additional information you need or if you need to see some more code.

1 Answers1

0

I believe the link you already posted has the right answers for you.

You need to make the class that handles the setup and show of the the tabBar implement UITabBarDelegate, not UITabBarControllerDelegate. Then you can use the right delegate method to retrieve when an item of the tabBar is clicked and check if it's then one you're interested in.

The method you want is tabBar:didSelectItem: (sent to the delegate when the user selects a tab bar item).

More info here.

Elvereth
  • 85
  • 8