6

Currently, I am trying to trigger the 'didSelectViewController' method programmatically via the following code:

self.tabController.selectedViewController 
        = [self.tabController.viewControllers objectAtIndex:NEWSTAB_INDEX];

However, the 'didSelectViewController' method wasn't called. How can I trigger the method without having to manually select the tab bar?

Zhen
  • 12,361
  • 38
  • 122
  • 199
  • 1
    N.B. the behavior of `tabBarController:didSelectViewController:` changed with iOS 3. In versions prior to 3, this method was called for both programmatic and user-initiated changes to the selected view controller. In iOS 3 and above, 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. – albertamg Sep 17 '11 at 09:41
  • I wonder why do you want to achieve this. – Raptor Dec 21 '11 at 09:59

2 Answers2

16
self.tabController.selectedIndex = NEWSTAB_INDEX;   // to actually switch to the controller (your code would work as well) - not sure if this does or not send the didSelectViewController: message to the delegate
[self.tabController.delegate tabBarController:self.tabController didSelectViewController:[self.tabController.viewControllers objectAtIndex:NEWSTAB_INDEX]];  // send didSelectViewController to the tabBarController delegate
alex-i
  • 5,406
  • 2
  • 36
  • 56
  • yes, it works for me also. But why do you have to do that? In my case, the UITabbarControllerDelegate is a separate class, NSObject, and implements the delegate methods. The problem is that if I switch the tab programaticaly, the delegate methods are not called. If you switch by clicking on the tabs themselves, it works. Could not yet figure out why it happens. – Zsolt May 09 '14 at 05:47
  • @Zsolt that's how the delegate was thought by Apple (triggered on user interaction), and it makes sense in a way. When changed programmatically, you already know that it changed, so there may be no point in triggering the delegate in some situations. – alex-i May 09 '14 at 07:28
  • now that I think about it, if I put the delegate method in the app delegate and use the app delegate as the tabbarcontroller delegate, changing the tab programmatically would trigger the delegate. So what you previously said might not be right. – Zsolt May 09 '14 at 08:57
0

For swift 3.0 you can programmatically call tabbar delegate method like this

self.tabController.selectedIndex = index (e.g. 0,1...etc)
self.tabController.delegate.tabBarController(self.tabController, didSelectViewController: self.tabController.viewControllers[index])
rohit
  • 56
  • 4