iOS: programmatically see view controllers in navi

2019-07-20 03:42发布

问题:

Is it possible to see which view controllers are in the navigation stack? New to Swift and iOS and just want to make sure navigation is happening properly and view controllers aren't stacking up inadvertently.

To clarify, it seems like you can use the viewControllers property in a UINavigationController, but for learning purposes, we're not using a navigation controller and doing the navigation manually through exit segues.

Can you programmatically print out the view controller hierarchy if not using a UINavigationController?

回答1:

Is it possible to see which view controllers are in the navigation stack?...Can you programmatically print out the view hierarchy if not using a UINavigationController?

You're talking about two complete different things here. Views and view controllers are not the same kind of object. They do both tend to be used in directed graphs of objects like themselves, but the graphs of those two kinds of objects are quite different. That is, a navigation controller is a kind of view controller that keeps a list of other view controllers, and (separately) a view keeps an array of the views that it contains. Finally most view controllers manage a single view that usually contains other views.

An easy way to see the hierarchy of views is to set a breakpoint on some line in one of your view controllers and use the debugger to po [self.view recursiveDescription], which will print (in the debugger) a description of the view and subviews that that view controller manages.

An even easier way to do it is to use Xcode's nifty view debugger, which gives you a layered view that you can examine in 3D:

The icon for that inspector looks like one rectangle on top of another:

You can certainly print out any graph of objects that your code can access, but from your comment it sounds like you'll have to write a method to do it. If you're not using a navigation controller, then there is no "navigation stack" to print out. You can implement your own version of a navigation stack, of course, but then it's up to you to provide a way to inspect it.



回答2:

UINavigationController holds its view controllers in a navigationController.viewControllers property, which is an array. You can inspect that value to see the navigation stack.

You could also use Xcode's view hierarchy debugger to visually see all the views in your app in 3D.

Another option is to use Facebook Chisel's pvc command which prints the view controller hierarchy.