1
votes

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.

3
How about [self.navigationController popToRootViewControllerAnimated:YES];Lord Zsolt
@LordZsolt, let me check.Nazik
@LordZsolt, sorry it's not working. any other suggestions.Nazik
You need to pass the instance of that controller where you want to pop to that class from where you want to pop. And then try to pop to that controller instead of creating a new instance.Exploring
Use: [[self navigationController] popToRootViewControllerAnimated:YES];Midhun MP

3 Answers

2
votes

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];
1
votes

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.

0
votes

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.