简体   繁体   中英

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.

eg

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
}

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
}

With respect to @Simon answer, I'm adding my answer, to check when you're using some drawer menu, this may help you to find exact root view controller check.

- (BOOL) checkImRoot:(id)controller {
    if(self.window.rootViewController) {
        if(self.window.rootViewController == (UIViewController *)controller) {
            return YES;
        }
    }
    return NO;
}

In example, I'm adding this method in app delegate file, and calling it like this to check,

if([[AppDelegate shareDelegate] checkImRoot:self]) {
     //Yeah, I'm a root vc
}else{
     //Noo, I'm a child vc
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM