iosxcodexcode6uitabbarcontrollertabbed-interface

Xcode Storyboard Tabbed application (UITabBarController) - tell when tab selected


Using Xcode 6 I have created an Tabbed Application using a storyboard with the supplied template.

I need a function to fire when the third tab of the UITabBarController is selected.

I can’t use the ViewDidLoad as I need it fire every time the view is accessed by clicking on the tab (not just the first time( and I can't use ViewWillAppear as I need specific behaviour when view is accessed via the tab as opposed to segued back to from subsequent (modal) view controllers.

Any advice would be appreciated. Many thanks in advance.


Solution

  • Implement this delegate method of UITabBarControllerDelegate on some UIViewController class

    - (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController {
    NSUInteger indexOfTab = [theTabBarController.viewControllers indexOfObject:viewController];
    // Your code here
        }
    

    OR

    You can subclass UITabBarController and override the following method.

    - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSUInteger indexOfTab = [[theTabBar items] indexOfObject:item];
    // Your code here}