oberbaum
oberbaum

Reputation: 2448

Programmatically call navigation controller back button on iOS

In a UINavigationController-based iPhone app, in a method I would like to perform the programmatic equivalent of the back button being pressed and going back a view.

i.e. automatically press the Jobs button as seen here:

Navigation Controller image

Is there a generic iOS call I can make, or is more information required?

Upvotes: 87

Views: 74233

Answers (5)

Steve Harrison
Steve Harrison

Reputation: 125480

UINavigationController's -popViewControllerAnimated: method should do what you want:

[navigationController popViewControllerAnimated:YES];

Upvotes: 191

Tal Zion
Tal Zion

Reputation: 6526

Swift 3.0

Back to the root view

self.navigationController?.popToRootViewController(animated: true)

Back to the previous view

self.navigationController?.popViewController(animated: true)

Swift 2.3

Back to the root view

self.navigationController?.popToRootViewControllerAnimated(true)

Back to the previous view

self.navigationController?.popViewControllerAnimated(true)

Upvotes: 23

Nishant Mahajan
Nishant Mahajan

Reputation: 264

[self.navigationController popViewControllerAnimates:YES];

is the best option but if you are nor on the same view controller class or your delegate changes before your back button method called then you can also try--

first you have to define back button---

UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: @"anyTitleForBackButton" style: UIBarButtonItemStyleBordered target: nil action: @selector(backButtonTapped)];

[[self navigationItem] setBackBarButtonItem: newBackButton];

[newBackButton release];

and then in backButtonTapped method you can call--

[self.navigationController pushViewController:desiredViewController animated:YES];

Upvotes: 6

Kevin Elliott
Kevin Elliott

Reputation: 2728

Assuming you don't actually want to PRESS the button programmatically, but simply copy the outcome of pressing the button, you should tell the navigation controller to pop the current view controller.

[self.navigationController popViewControllerAnimated:YES];

This will remove it from the stack, and return you to the previous view controller.

Upvotes: 24

Niels Castle
Niels Castle

Reputation: 8069

You should call

popViewControllerAnimated:

which is the opposite of adding view controllers with pushViewController:animated:

Upvotes: 7

Related Questions