简体   繁体   中英

How to go back to the first view

示例情节提要

Assuming i have a setup like the above, how would one go back to the first view (eg. The one with the Label) ?

I am asking this because i am not sure if is there a particular reason why there would be multiple navigation controllers setup similar to above.

I came across this problem because popToRootViewController will only go back to the first view of that navi controller. Eg. if i was at one the views of the 2nd navigation controller and i were to run popToViewController, it will only go back to the first view controller of the 2nd navigation controller. I have since solved the problem by removing the other navigation controller but my curiosity had to be resolved.

As I stated in the comment, the second view controller is almost certainly unnecessary (but this isn't entirely necessarily the case), so your best bet is most likely to simply to remove that second navigation controller.

With that said though, how you would get back to the original view controller with the existing set up would depend largely on how you got to the current view controller.

If the second navigation controller is pushed on to the first navigation controller's navigation stack, then from any view after the second view controller, you could do something like this:

self.navigationController?.navigationController?.popToRootViewControllerAnimated(true)

Otherwise, if the second navigation controller were presented modally, you could dismiss it from any of the view controllers in its navigation stack with the following code:

self.navigationController?.dismissViewControllerAnimated(true, completion: nil)

It's important to remember that UINavigationController is a subclass of UIViewController and as such, any method we can call on the latter can also be called on the former.

One simple (Hacky) approach is to maintain a global pointer to your first navigation controller (Maybe in the AppDelegate or .pch file), and whenever you want to go your root controller, you can just say dismissViewController:animated , and then popToRootViewController .

Should work in all the cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM