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

Bhumi Goklani picture Bhumi Goklani · Dec 9, 2014 · Viewed 16.2k times · Source

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

Answer

Simon McLoughlin picture Simon McLoughlin · Dec 9, 2014

[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
}