0

My question is simple. I have a storyboard uses navigation controller and views, lets say view1, view2, view3 and view4. Flow between them is like following:

view1 --> view2 (push)
view2 --> view3 (push)
view3 --> view4 (push)
view4 --> view2 (push)

What I want to do is, when I click on back button at view2, I always want to go to view1 but not never view4. What logic should I follow to do this?

note: non of them is root view.

birdcage
  • 2,638
  • 4
  • 35
  • 58

2 Answers2

3

For this you can do one of two things.

Either an unwind segue...

In ViewController1 put a method like...

- (IBAction)unwindBackToHere:(UIStoryBoardSegue *)segue
{
    // do something
}

Then in the storyboard drag from the "done" button to the green "exit" door underneath the view controller and you should see the method you created.

This new "segue" will pop from ViewController4 all the way back to ViewController1.

You can then use it to do other stuff like reloading the screen etc...

Or you can just pop back to it.

//in ViewController4
- (void)doneButtonPressed
{
    [self.navigationCongtroller popToViewController:viewController1 animated:YES];
}

This is more cumbersome though as it means getting hold of view controller 1 first.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 1
    In that case, you should hide the back button of view 2, or else it won't use the unwind and go back to view4. – galrito Jul 17 '14 at 15:21
  • 1
    Yep, @galrito is right. The back button will go from View4 to View3 which is fine if you want to allow that but if not then you can hide it fairly easily. – Fogmeister Jul 17 '14 at 15:30
0

When you are on the view4 and want to push view2, do not use segues and push an array of viewControllers to UINavigationController, like so:

NSArray *viewControllers = @[view1, view2];
[self.navigationController setViewControllers:viewControllers animated:YES];

This will remove view4 from the stack and have the hierarchy you want.

Another option is replace the back button of view2 with your own and the use the following on its action method:

[self.navigationController popToViewController:view1 animated:YES];
galrito
  • 352
  • 1
  • 7