26

I'm trying to animate the transitions between tabs in my UITabBarController, which is working fine when I push on the tab buttons. However, when I switch tabs programmatically by calling

[self.tabBarController setSelectedIndex:2];

in a swipe gesture recognizer, the shouldSelectViewController function is NOT being called in my UITabBarControllerDelegate delegate, and therefore my animation isn't being triggered.

Is there a way to accomplish what I want? Can I programmatically trigger the tab switch differently perhaps so that the shouldSelectViewController function gets called?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
herrtim
  • 2,697
  • 1
  • 26
  • 36
  • 1
    Yes you can progmatically call the delegate. It will work. [self.tabBarController setSelectedIndex:2]; will give the highlighted effect to the corresponding tabbaritem – Puneet Sharma Jul 16 '13 at 12:40
  • @Puneet How do I call the UITabBarControllerDelegate delegate's shouldSelectViewController method? – herrtim Jul 16 '13 at 12:54
  • 2
    If you have set tabbarcontroller as the root of the app, you must have set its delegate method at the app delegate. So you can call it from other view Comtrollers by creating an object of AppDelegate. you need to pass two parameters , one is tabbarController, which you can get f4rom appdelegate as well and other is the ViewController you want to show. – Puneet Sharma Jul 16 '13 at 12:56

1 Answers1

48

If you have implemented - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController in your tabBarController's delegate than you can call it manually.

[self.tabBarController.delegate tabBarController:self.tabBarController shouldSelectViewController:[[tabBar viewControllers] objectAtIndex:2]];
[self.tabBarController setSelectedIndex:2];

Hope this helps.

Kapil Choubisa
  • 5,152
  • 9
  • 65
  • 100
  • Perfect, thanks. Along with Puneet's comments above, I got it working! – herrtim Jul 16 '13 at 13:33
  • 13
    No, delegates methods are NOT for manual calling! The method should be called if something happen. With your solution i could put `return NO` in `- (BOOL)tabBarController: shouldSelectViewController:` and controller still will be selected. – Jakub Feb 05 '15 at 21:00
  • Genius. Thanks alot. – NaXir Jul 31 '16 at 12:06
  • Like @Kuba stated, do not call directly the delegate method. Instead define a separate method where you define the animation. Then have the delegate method call that method for the case of manual tab selection, and call the method yourself before `[self.tabBarController setSelectedIndex:2];` to trigger the animation programmatically. – atineoSE Nov 08 '17 at 15:08