问题
I got an app with my custom TabBar Controller Class.
I tried to implement tabbar controller delegate method:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
NSLog(@"%i",tabBarController.selectedIndex);
}
But it doesnt work. Why?
in ViewDidLoad
i write:
self.tabBarController.delegate = self;
And in .h i implement:
@interface BaseViewController : UITabBarController <UITabBarControllerDelegate>
回答1:
In your custom TabBarController, do not use
self.tabBarController.delegate = self;
But use
self.delegate = self;
.tabBarController returns the nearest ancestor in the view controller hierarchy that is a tab bar controller, but your custom TabBarController IS the controller you want to target, so no need to search in its hierarchy
回答2:
You have said, that it's your custom TabBarController. What is the customisation you've done? If you changed the TabBar panel and replaced it with your own to use
setSelectedIndex:
setSelectedViewController:
methods manually, then you should call delegate's methods manually too.
According to the Apple's documentation:
There are two types of user-initiated changes that can occur on a tab bar:
- The user can select a tab.
- The user can rearrange the tabs.
Both types of changes are reported to the tab bar controller’s delegate, which is an object that conforms to the UITabBarControllerDelegate protocol.
Also check the UITabBarControllerDelegate Protocol Reference
In iOS v3.0 and later, the tab bar controller calls this method regardless of whether the > selected view controller changed. In addition, 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.
Delegate will respond only if user interacts with its UITabBar control.
来源:https://stackoverflow.com/questions/9545126/cant-use-tabbar-delegate-methods