0

In one of my ViewControllers I have the following code:

- (void)viewDidLoad
{
    UITabBarController *tabBarController = (UITabBarController*)[UIApplication sharedApplication].keyWindow.rootViewController ;
    [tabBarController setDelegate:self];
}

and :

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController: (UIViewController*)viewController {
    NSLog(@"Yup!");
}

Whenever I switch tabs in my multi-tab setup, the console spits out

Yup

just as expected.

However, when I add

UITabBarController *tabController = (UITabBarController*)self.window.rootViewController;
tabController.selectedIndex = 1;

to my AppDelegate.m's

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:

the 'Yup' doesn't show anymore.

How come?

Sjakelien
  • 2,255
  • 3
  • 25
  • 43

1 Answers1

0

didSelectViewController will call when you select/change tabs from the app itself, it will not call when you set the selectedIndex programmatically

tabController.selectedIndex = 1; , will mostly useful when you want to set default tab or want to change the selectedIndex programmatically

From apple doc:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController

it is called only in response to user taps in the tab bar and is not called when your code changes the tab bar contents programmatically.

You can try calling that method manually like this:

- (void) selectedItemWithIndex:(int)value {
    tabbar.selectedIndex = value;
    [self tabBarController:tabbar didSelectViewController:tabbar.viewControllers.firstObject];//place you vc here by array or manually
}

Ref: https://stackoverflow.com/a/30700712/4557505

Community
  • 1
  • 1
HardikDG
  • 5,892
  • 2
  • 26
  • 55
  • That makes sense, but I would expect that the 'Yup' would nevertheless kick in when I change tabs – Sjakelien Apr 05 '16 at 15:26
  • I still don't see a reason why a method in the AppDelegate will cancel other functionality. And I am too old to do Swift. – Sjakelien Apr 05 '16 at 16:19
  • where did it cancel the functionality it is not implemented like this as I quoted from the apple doc, you are just setting a property – HardikDG Apr 05 '16 at 16:27