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?
Asked
Active
Viewed 3.5k times
60

juco
- 6,331
- 3
- 25
- 42

Timur Mustafaev
- 4,869
- 9
- 63
- 109
-
May be you just want to pop to previous view? – Nekto Oct 04 '11 at 09:50
6 Answers
176
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 returnsnil
if there is nothing to pop.

Top-Master
- 7,611
- 5
- 39
- 71

Mann
- 2,118
- 1
- 18
- 18
16
If by pressing "Back" button you mean just to go to the previous view controller, you can just call:
[self.navigationController popViewControllerAnimated:YES];

Bartek
- 1,986
- 1
- 14
- 21
9
Here is the swift method
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}

MGM
- 2,379
- 1
- 19
- 13
-
12
-
..or just (swift 4): `navigationController?.popViewController(animated: true)` – Sentry.co May 08 '18 at 09:56
3
Swift 5
self.navigationController?.popViewController(animated: true)
Usage in a code snippet:
func unwindViewController() {
self.navigationController?.popViewController(animated: true)
}

Amit
- 310
- 1
- 3
- 15
0
Here is how I did it in Swift 3
_ = self.navigationController?.popViewController(animated: true)
_
is used to suppress the ugly warning generated by XCode.

Jay Mayu
- 17,023
- 32
- 114
- 148
-
1You do not let, so you can just write: _ = self.navigationController?.popViewController(animated: true) – Brian Ogden Sep 18 '17 at 04:09
-
0
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];

Mohit
- 126
- 2
- 10