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

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


[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.firstif vc == self.navigationController?.visibleViewController {    //Code Here}


Whenever you push any view controller via navigation controller, it manages these view controllers on a stack which is maintained in Last In First Out manner. So if your current view controller is root controller than there can be only one object in the stack. You can check that stack via this code

if([self.navigationController.viewControllers count] == 1)  {     //Current view controller is root controller  }


in your current View controller's viewDidLoad just check self.navigationController.viewControllers.count == 1 mean you are currently in rootview of your navigationstack. make sure you haven't present viewcontroller.

if(self.navigationController.viewControllers.count == 1){    //do what you want}