Question

Let me explain clearly.

I have a tabbarcontoller in the viewcontroller which is the main view controller of the single view application project.

I added a tabbarcontroller to the viewcontroller as the subview. In the tabbarcontroller, I added two navigation controllers like below image,

enter image description here

I have added three(named First, Second, Third) more viewcontrollers as new file.

If I navigate from one viewcontroller to other in a tab using below,

third =  [[Third alloc] initWithNibName:@"Third" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:third animated:YES];

If I switch to next tab and come back to the previous tab, it should popto the previous view controller, how to do this?

I tried

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{

    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}

not succeed,

I also tried,

[third popto];

In the third viewcontroller,

-(void)popto
{
  [self.navigationController popViewControllerAnimated:YES];
}

nothing happened.

Now, I have to click the tab again to poptoviewcontroller to the first viewcontroller.

Any ideas will be highly appreciated.

Was it helpful?

Solution 2

Try the below code snippet

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
 UINavigationController *navController = (UINavigationController*)viewController;

if (navController && ([[navController viewControllers] count] > 0))
{
    [navController popToRootViewControllerAnimated:NO];
}
return YES;
}

Hope it may work for you.

OTHER TIPS

You should try using

[viewController.navigationController  popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];

instead of

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];

How about overriding UITabbarController for a custom one and implement the following method:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

Next loop trough all the 'viewcontrollers' of the tabbar (in this case the navigation controllers) and call on all the navigation controllers popToRootViewController.

This might work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top