Get the current view controller from the app delegate

前端 未结 11 1990
悲哀的现实
悲哀的现实 2020-11-30 22:46

i am new to ios. I need to know the current view controller from app delegate.. i have no idea about this and i don\'t knowto implement this. i am using this code toimplemn

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 23:13

    This helped me to find the visible view controller. I searched for existing methods and didn't find any. So I wrote my own custom one.

    -(id)getCurrentViewController
    {
        id WindowRootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    
        id currentViewController = [self findTopViewController:WindowRootVC];
    
        return currentViewController;
    }
    
    -(id)findTopViewController:(id)inController
    {
        /* if ur using any Customs classes, do like this.
         * Here SlideNavigationController is a subclass of UINavigationController.
         * And ensure you check the custom classes before native controllers , if u have any in your hierarchy.
        if ([inController isKindOfClass:[SlideNavigationController class]])
        {
            return [self findTopViewController:[inController visibleViewController]];
        }
        else */
        if ([inController isKindOfClass:[UITabBarController class]])
        {
            return [self findTopViewController:[inController selectedViewController]];
        }
        else if ([inController isKindOfClass:[UINavigationController class]])
        {
            return [self findTopViewController:[inController visibleViewController]];
        }
        else if ([inController isKindOfClass:[UIViewController class]])
        {
            return inController;
        }
        else
        {
            NSLog(@"Unhandled ViewController class : %@",inController);
            return nil;
        }
    }
    

    And sample use :

    -(void)someMethod
    {
        id currentVC = [self getCurrentViewController];
            if (currentVC)
            {
                NSLog(@"currentVC :%@",currentVC);
            }
    }
    

提交回复
热议问题