Search code examples
iosobjective-cuitabbarcontrollersegue

How can I prevent an unwind segue from UITabBar?


I have a Show segue that is embedded in a UITabBarController. I want to prevent an unwind segue when I tap the currently selected tab unless a certain condition is met. I've tried using shouldPerformSegueWithIdentifier and canPerformUnwindSegueAction but neither appear to be triggered when unwinding in this way.


Solution

  • Not sure what you mean by unwind segue on a tab bar, but if you want to prevent a tab change, there is a delegate function on UITabBarController for that purpose.

    Add the protocol to your tab bar class.

    @interface YourTabbarViewController () <UITabBarControllerDelegate>
    
    @end
    

    Assign the delegate, then later implement the function.

    @implementation YourTabbarViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.delegate = self;
    }
    
    - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
        if (preventTabChange)
            return NO;
    
        return YES;
    }
    

    UPDATE

    OK, assuming you have set up relevant parts as on this picture, and you want to prevent the unwind from B to A if certain conditions are met. My solution as described above will work.

    enter image description here

    As you will get a query/notification whenever the Navigation Controller is about to become active, you could create your own sub-class of that to hold whatever information you need to decide if it should be allowed to show or unwind from a sub-view controller. In that case your prevention could look like this (expanding the shouldSelectViewController above):

    - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
        if ([viewController isKindOfClass:[YourNavigationController class]]) {
            if ([(YourNavigationController *)viewController preventUnwind])
                return NO;
        }
    
        return YES;
    }
    

    Note that I purposely chose preventUnwind as a flag in your custom class to say what to do. This will default to NO when you move to the view controller, and thus allowing that.

    Don't forget to set YourTabbarViewController as the class for the Tabbar View Controller and YourNavigationController as the Navigation Controller in the picture.