I'm trying to figure out how to catch the event that controls the switch tabs on the
UITabBarController
. How could I accomplish this?
Asked
Active
Viewed 2.3k times
31

Gilles 'SO- stop being evil'
- 104,111
- 38
- 209
- 254

Yan
- 1,424
- 4
- 21
- 44
5 Answers
37
Implement UITabBarControllerDelegate
e.g. in your app delegate's applicationDidFinishLaunching
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
tabBarController.delegate = self;
[window addSubview:tabBarController.view];
}
Then implement either:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
The first method is called before the view switch and gives you a chance to 'veto' the view switch by returning NO
The second method is called after the view switch has taken place

cidered
- 3,241
- 3
- 25
- 20
15
If you are using storyboard, do this
in didFinishLaunchingWithOptions
UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
[tabBar setDelegate:self];
Also in AppDelegate, keep <UITabBarControllerDelegate>
And then
-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
//Write your code here
}

nithinreddy
- 6,167
- 4
- 38
- 44
6
Better late than never. In case of swift 4 you can do it in the following way.
tabBarViewController.delegate = self
And implement UITabBarDelegate
in your class.
You will get the callback in
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
//Stuff to do
}

vedant shirke
- 359
- 4
- 9
5
Have a look at the following method in UITabBarControllerDelegate:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
Tells the delegate that the user selected an item in the tab bar.

Vladimir
- 170,431
- 36
- 387
- 313