Hermann Klecker
Hermann Klecker

Reputation: 14068

How to determine if a ViewController is top level or not?

I have a tab bar driven app.

The app has some view controllers that are stacked on each other the usual way. Some of these view controllers may be top level - meaning instantiated directly from the tab bar controller. Those do not have a "back" button in their navigation bar.

Some of these can be called at many points within the call stack. Meaning they could be called from some other view controller and not directly from the tab bar.

I am looking for a smart way to determine programatically whether the current view controller currently has a "back" button in its nav bar or not. (If it does not then I want to display some other bar item at that place.)

Any hint is appreciated. :)

Upvotes: 2

Views: 7615

Answers (4)

jemmons
jemmons

Reputation: 18657

You could ask your view controller for it's -navigationController, ask the navigation controller for its -viewControllers stack, and see what the -count of that stack is.

The currently-showing view controller is the "last" item in the stack (index n-1). The "back" view controller second-to-last (n-2 — n being the count of the stack). So if the count of the stack is 1, that means you've reached the top. There's nothing in the stack to go back to and no back button will be displayed.

Upvotes: 3

Legolas
Legolas

Reputation: 12325

Well... from what you are describing, I can understand that you have a UITabBarController with a list of view controller in each tab, and each view controller is a navigation controller, which further leads to new views. And you are interested in finding if a particular view is the first view or the second view, and so forth.

Interestingly, there is a way to do this. The navigation controller is basically a viewController array with views added to the index of the navigationController. The first view will be in index 0. If you perform a pushViewController, the newViewController is placed at index 1.

Just check for the index count of the self.navigationController of that particular view. If it is greater than 1, you can be certain that it is not the initial view.

You can also check for the backBarButtonItem property, but then again, it may not be needed. The viewControllers array count should do.

Upvotes: 5

Tim
Tim

Reputation: 60110

Consider just getting the index of the view controller within the navigation controller's viewControllers array property. If it's zero, then the view controller is the top controller (without a back button).

Upvotes: 2

jbat100
jbat100

Reputation: 16827

UINavigationController has topViewController and visibleViewController properties which could help you out. If you just want to know if there is a back button or not you can check the backBarButtonItem property of the UINavigationItem and see if it is non-nil and non-hidden.

Upvotes: 0

Related Questions