Programmatically call navigation controller back button on iOS

IosObjective CButtonUinavigationcontroller

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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

[navigationController popViewControllerAnimated:YES];

Solution 2 - Ios

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.

Solution 3 - Ios

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)

Solution 4 - Ios

You should call

popViewControllerAnimated:

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

Solution 5 - Ios

[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];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionoberbaumView Question on Stackoverflow
Solution 1 - IosSteve HarrisonView Answer on Stackoverflow
Solution 2 - IosKevin ElliottView Answer on Stackoverflow
Solution 3 - IosTal ZionView Answer on Stackoverflow
Solution 4 - IosNiels CastleView Answer on Stackoverflow
Solution 5 - IosNishant MahajanView Answer on Stackoverflow