Search code examples
iphoneobjective-ciosdelegatestabbar

How do I execute a method every time a tab is pressed from the tab bar?


I want to run a method every time a tab from the tab bar is pressed in my app. How do I do this? I have a tab bar controller in my storyboard (built when i chose tab bar application when I created the project).

For example I want to print 'tab button pressed to the console every time a tab button is pressed.

I tried adding this in the app delegate without any luck:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{

    NSLog(@"Tab Button Pressed");

}

This is probably quite simple but I'm missing something.


Solution

  • If you are using xcode 4.2.x then the templates set up the UITabBarController in code in the appDelegate

    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
    self.tabBarController.delegate = self;    //<---- Add this line
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
    self.window.rootViewController = self.tabBarController;
    

    If you have an old style project or built your structure using interface builder then:

    1. Right click the Tab bar controller in the objects view
    2. Locate the delegate outlet
    3. Connect the delegate outlet to the File's Owner

    enter image description here enter image description here