UINavigationController popToRootViewControllerAnimated goes back one by one

217 Views Asked by At

This is the simple code I am calling to go back to rootViewController of UINavigationController :

-(void)viewWillDisappear:(BOOL)animated
{
     [self.navigationController popToRootViewControllerAnimated:YES];   
     [super viewWillDisappear:animated];
}  

But the back navigation occurs one by one.
Say I have 3 viewControllers - A, B, C.
A -> B -> C
What I want on back of C is :
C -> A
But on using popToRootViewControllerAnimated, this is how back navigation appears :
C -> B -> A

2

There are 2 best solutions below

0
On

Try to use

[self.navigationController popToViewController:VC animated:YES] 

instead of

[self.navigationController popToRootViewControllerAnimated:YES]

wrap this in a category and add your logic to make it more modular. You can jump to any view controller.

Another way of doing is that swizzling popToRootViewControllerAnimated which I think you should definitely avoid since this is a general method used heavily app-wise. You can modify it's actual behavior with your swizzled behavior.

See http://nshipster.com/method-swizzling/ for swizzling.

0
On

Try to realize what should happen

-(void)viewWillDisappear:(BOOL)animated
  {
    [self.navigationController popToRootViewControllerAnimated:YES];
    [super viewWillDisappear:animated];

  }

1st you calling viewWillDisappear method. which will execute first. after executing this Your current view is "B". Then executes "[self.navigationController popToRootViewControllerAnimated:YES]" so. you will see A<-B (view A backed from B)

so, you will see in all A<-B<-C.

To resolve this issue try to execute popToRootViewControllerAnimated method outside viewWillDisappear method