Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if navigation controller is pushed or is a root view controller?

I want to check if the view controller i am in is root view controller or is pushed on some navigation controller.

like image 738
Bhumi Goklani Avatar asked Dec 09 '14 11:12

Bhumi Goklani


People also ask

How do I know if my view controller is root view controller?

The root view controller is simply the view controller that sits at the bottom of the navigation stack. You can access the navigation controller's array of view controllers through its viewControllers property. To access the root view controller, we ask for the first item of the array of view controllers.

How do I know if ViewController is visible?

The view's window property is non-nil if a view is currently visible, so check the main view in the view controller: Invoking the view method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded.

What is a root controller?

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller's view as the content view of the window.


1 Answers

[self.navigationController viewControllers];

will return an array of all the viewControllers on the stack. Simply compare the first element in this array to see is the controller the root or not.

e.g.

UIViewController *vc = [[self.navigationController viewControllers] firstObject];

if([vc isEqual: <viewController to check> ])
{
    // code here
}

EDIT: Add Swift

let vc = self.navigationController?.viewControllers.first
if vc == self.navigationController?.visibleViewController {
    //Code Here
}
like image 100
Simon McLoughlin Avatar answered Sep 22 '22 03:09

Simon McLoughlin