24

I have a Navigation Controller with a View Controller displaying a button. The button is linked to another View Controller using a push segue which automatically adds a top navigation bar with a back button. This all works fine. Pressing the back button slides off the 2nd view and returns to the 1st.

I have a button on the 2nd View Controller, that when pressed runs some code and a delegate call back to the 1st View Controller. Again this works fine.

Now I just need to dismiss the 2nd pushed View from code as if the back button was pressed. I have tried using dismissModalViewCcontrollerAnimated and dismissViewControllerAnimated, however they both dismiss the whole Navigation Controller which removes view 2 and 1 (returning bak to my main menu).

Whats the correct way to slide off the view.

Darren
  • 10,182
  • 20
  • 95
  • 162

6 Answers6

38

Obtain a reference to your UINavigationController and call

- (UIViewController *)popViewControllerAnimated:(BOOL)animated

on it.

Stavash
  • 14,244
  • 5
  • 52
  • 80
  • 7
    Thanks. That put me on the right path for a quick Google search. This worked [self.navigationController popViewControllerAnimated:YES]; – Darren Feb 25 '12 at 16:10
  • That's still moving back two levels for me, not just dismissing the last-pushed view. – Oscar Jan 17 '20 at 13:21
12

In Swift it would be calling the method

navigationController?.popViewController(animated: true)
אורי orihpt
  • 2,358
  • 2
  • 16
  • 41
Garrett Cox
  • 703
  • 6
  • 10
3

If we use push segue, then use popViewController

@IBAction func backButtonClicked(_ sender: Any) {
    self.navigationController?.popViewController(animated: false)
}
Alvin George
  • 14,148
  • 92
  • 64
2

In swift you can also call:

self.navigationController?.popToRootViewControllerAnimated(true)
jnwagstaff
  • 226
  • 1
  • 12
2

On Objective-C is

[self.navigationController popViewControllerAnimated:YES];

for a jump to the first root controller

[self.navigationController popToRootViewControllerAnimated:YES];

or is a possible move to the specific controller

[self.navigationController popToViewController:(nonnull UIViewController *) animated:(BOOL)];

animation specific animation process of move the controller. If the animation is false the controller will appear without animations. The UIViewController must be from one which is on the stack.

Jan Damek
  • 431
  • 4
  • 6
0

If NavViewController is used with UIModalPresentationFullScreen then the below line will work

self.navigationController?.dismiss(animated: true, completion: nil)
arun-r
  • 3,104
  • 2
  • 22
  • 20