How to press "Back" button in UINavigationController programmatically

IphoneObjective CIosUiviewcontrollerUinavigationcontroller

Iphone Problem Overview


I have a UIViewController called FriendsViewController inside a UINavigationController. And a second UIViewController called FriendsDetailedViewController. When navigating from the first view controller to the second, I want to programmatically press the Back button when needed. How to do this?

Iphone Solutions


Solution 1 - Iphone

Simply use

[self.navigationController popViewControllerAnimated:YES]

from FriendsDetailedViewController. Your view will be popped out i.e. the behavior of back button.

>Note that it returns UIViewController on normally, and returns nil if there is nothing to pop.

Solution 2 - Iphone

If by pressing "Back" button you mean just to go to the previous view controller, you can just call:

[self.navigationController popViewControllerAnimated:YES];

Solution 3 - Iphone

Here is the swift method

if let navController = self.navigationController {
    navController.popViewControllerAnimated(true)
}

Solution 4 - Iphone

Swift 5

 self.navigationController?.popViewController(animated: true)

Usage in a code snippet:

func unwindViewController() {
    self.navigationController?.popViewController(animated: true)
}

Solution 5 - Iphone

Here is how I did it in Swift 3

_ = self.navigationController?.popViewController(animated: true)

_ is used to suppress the ugly warning generated by XCode.

Solution 6 - Iphone

  1. When you pop in current NavigationController Then

In Swift

self.navigationController?.popViewControllerAnimated(true)

Objective C

[self.navigationController popViewControllerAnimated:YES];

2) When you back another Navigation controller Then

In Swift

let story = UIStoryboard(name: "Main", bundle: nil)
let pushVC = story.instantiateViewControllerWithIdentifier("PushVC")
let navigation = story.instantiateViewControllerWithIdentifier("homeNavigation") as! UINavigationController
navigation.pushViewController(pushVC!, animated: true)

In Objective C

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
pushVC* ObjectOfPushVC = [storyboard instantiateViewControllerWithIdentifier:@"pushVC"];

[self.navigationController pushViewController:ObjectOfPushVC 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
QuestionTimur MustafaevView Question on Stackoverflow
Solution 1 - IphoneMannView Answer on Stackoverflow
Solution 2 - IphoneBartekView Answer on Stackoverflow
Solution 3 - IphoneMGMView Answer on Stackoverflow
Solution 4 - IphoneAmitView Answer on Stackoverflow
Solution 5 - IphoneJay MayuView Answer on Stackoverflow
Solution 6 - IphoneMohitView Answer on Stackoverflow