Suppose I have view controllers named A, B, C, D. I am using push to go from A -> B -> C. Now I want to go to D from C and when I press back button from D, it should go to A. How Can I do that? Any suggestions?
2
-
use this -> self.navigationController?.popToRootViewControllerAnimated(true)Avinash651– Avinash6512016-03-11 10:07:16 +00:00Commented Mar 11, 2016 at 10:07
-
But It will take me to A.. I want to go directly from C to D.. and It should Pop All the view Controllers.Riddhi Shah– Riddhi Shah2016-03-11 10:14:30 +00:00Commented Mar 11, 2016 at 10:14
Add a comment
|
3 Answers
You need to modify your back button with a custom one, and add an action which will pop you to the rootViewController inside that UINavigationController you are currently. (popToRootViewController means removing all other controllers from the navigation stack and go the first one)
On your last viewController put these lines:
Objective-C
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Go to root" style:UIBarButtonItemStylePlain target:self action:@selector(popToRootNavigationViewController:)];
}
- (void)popToRootNavigationViewController:(UIBarButtonItem *)button {
[self.navigationController popToRootViewControllerAnimated:YES];
}
Swift
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Go to root", style: UIBarButtonItemStyle.Plain, target: self, action: "popToRootNavigationViewController:")
}
func popToRootNavigationViewController(sender: UIBarButtonItem) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
2 Comments
Riddhi Shah
In function
self.navigationController?. popToRootViewControllerAnimated(true) should be used in place of self.navigationController?.popViewControllerAnimated(true)Riddie
@RiddhiShah yeah a typo there, thank you for pointing out! Updated :)
Using a UINavigationController you can call popToRootViewControllerAnimated(_:), it will take you back to the first controller of your pile.
So use a NavController, set A as root, and in D, popToRootViewControllerAnimated(true)