How to access the stack in UINavigationController

2019-02-07 21:22发布

viewControllers

The view controllers currently on the navigation stack.

@property(nonatomic, copy) NSArray * viewControllers

Discussion

The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array.

Assigning a new array of view controllers to this property is equivalent to calling the setViewControllers:animated: method with the animated parameter set to NO.

I am confused how to access the the stack I have three views in the navigation controller – root view controller, sti testing location, sti map.

How can I access the stack?

3条回答
戒情不戒烟
2楼-- · 2019-02-07 21:37

The array returned by the viewControllers property is the stack. They are ordered in the same sequence that they were shown. the controller at index 0 is the controller you started with. The controller you are currently looking at is the highest index. Since indexes are counted from zero the last item index will be the count (n)-1.

Now you say "views" in your post. There is a difference between views and view controllers. If you are talking about multiple pieces that are all visible at the same time then you are talking about views not view controllers. The Navigation Controller is for handling multiple view controllers. If you are dealing with views than you want to access the subviews of the current view controller's view myViewController.view.subviews They order themselves in a similar way.

查看更多
走好不送
3楼-- · 2019-02-07 21:51

Assuming you meant that your navigation controller has three view controllers, you should be able to access the navigation controller from any of three view controllers using self.navigationController.

So if you want to get the second view controller in the stack, you should do –

UIViewController * viewController = [self.navigationController.viewControllers objectAtIndex:1];

This is assuming that there are at least two view controllers on the navigation controller.

查看更多
放荡不羁爱自由
4楼-- · 2019-02-07 21:56

UINavigationControllers have a property called viewControllers as you have stated above. Since this is an array of View Controllers, referencing a specific view controller in this hierarchy is no different than accessing any other object in an array.

UIViewController *theControllerYouWant = [self.navigationController.viewControllers objectAtIndex:(theIndexOfYourViewController)];

In addition check out the Navigation Controllers article in the iOS Developer Library, specifically the section called 'Modifying the Navigation Stack'.

查看更多
登录 后发表回答