19
votes

Thanks for reading my question.

I'm trying to implement a popup menu when a user clicks the tab with the index of 4. So I'm trying to prevent the tabbar from switching viewcontroller when index 4 is pressed.

Here is my code:

- (BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if(viewController == [tabBarController.viewControllers objectAtIndex:4]){        
        NSLog(@"NO");
        return NO;
    }else{
        NSLog(@"YES");
        return YES;
    }

}

I've implemented the UITabBarControllerDelegate and self.delegate = self; in the viewDidLoad and it works but just one time.

When I click the index 4 tab the menu shows and the tabbar doesn't switch view (GREAT), but when I click it again the view changes even if I get the Log "NO". What could be the problem here?

Thanks you for any suggestions!

SOLVED

Thanks to Kasaname's answer below I solved it by adding selectedindex and set it to a flag index (prevtab). I change the prevtab to the index of the last selected tab, exept for when the user selects index 4. My final code:

- (BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if(viewController == [tabBarController.viewControllers objectAtIndex:4]){
        self.selectedIndex = prevTab; //only change in this method       
        return NO;
    }else{        
        return YES;
    }

}
2
Why don't u use just empty ViewController for the 4th tab? - NSDmitry
Add a breakpoint to viewDidAppear/viewWillAppear methods of your view controller. As per documentation, this method is called regardsless of whether the selected view controller changed. - Abhishek Bedi
@ProFFeSSoR: What do you mean by empty ViewController for the 4th tab? - Abhishek Bedi
@PaperThick: Why are you using viewController in if condition instead of using the selectedIndex? - Abhishek Bedi

2 Answers

15
votes

This is how you can stop/prevent Tabbar items to switch your tab on tabbar item click

For Swift 3.0

Make sure you have implemented UITabBarControllerDelegate and set UITabbarController's delegate to self

then override this delegate in your controller

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

    if viewController == tabBarController.viewControllers?[2] {
        return false
    } else {
        return true
    }
}
5
votes
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if (tabBarController.selectedIndex == 0) {

    } else if (tabBarController.selectedIndex == 1) {

    } else if (tabBarController.selectedIndex == 2) {

    }
}

why dont u use this delegate Use this delegate it will work i suppose