问题
when we touch the tabbaritem of the tabbarcontroller the delegate methods are called:
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
but when try to do the same thing programmatically, i.e.
[self.tabbarController setSelectedIndex:selectedIndexNo];
or
[self.tabBarController setSelectedViewController:[self.tabBarController.viewControllers objectAtIndex:0]];
the delegate methods are not called. What is the reason for that?
回答1:
override UITabBarController setSelectedIndex:
-(void)setSelectedIndex:(NSUInteger)selectedIndex
{
//must call super function.
[super setSelectedIndex:selectedIndex];
[self myMethod];
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
[self myMethod];
}
回答2:
When you are setting them yourself via code, than you are aware that this is the time when the delegate method will be called. so whatever you wish to do you can do it at the time of setting the index programmatically. Say you want to call a method aMethod on tabbardelegate being called. you can call the method as soon as you set the index.
[self.tabbarController setSelectedIndex:selectedIndexNo];
[self aMethod];
来源:https://stackoverflow.com/questions/15278537/why-does-selecting-a-tabbarcontroller-index-programatically-doesnt-call-delegate