Search code examples
iospresentviewcontroller

How to find current visible viewController in iOS


We know , if your viewController have been contain UINavigationController ,

you can find your current visible view controller by 'self.navigationController.visibleViewController' .

But I you present a view controller , how to find current visible controller ?

For Example :

code one :
------
AVClr *avclr = [[AVClr alloc]init] ;
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate ;
appDelegate.window.rootViewController = avclr ;
[avclr presentViewController:loginNavClr animated:YES completion:nil] ;

---> now , display avclr

code two:
------
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate ;
UIViewController *currentVisibleViewController = appDelegate.window.rootViewController ;
BVClr *bvclr = [[BVClr alloc]init] ;
[currentVisibleViewController presentViewController:bvclr animated:YES completion:nil] ;

---> now , display bvclr

code three:
------
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate ;
UIViewController *currentVisibleViewController = appDelegate.window.rootViewController ;
CVClr *cvclr = [[CVClr alloc]init] ;
[currentVisibleViewController presentViewController:cvclr animated:YES completion:nil] ;

---> Error , can not display cvclr , because avclr is a rootViewController and avclr present bvclr , so display bvclr .

Question:

But we know ,code three in another .m file , so we don't know who is the rootViewController . so If I present cvclr , the result is unexpect !

In the circumstances ,how to display cvclr


Solution

  • -(UIViewController *)getVisibleViewController : (UIViewController *)rootViewController
    {
        UIViewController *rootVC = rootViewController;
        if (rootVC == nil)
        {
            rootVC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        }
    
        if ([rootVC presentedViewController] == nil)
        {
            return rootVC;
        }
    
        if ([rootVC presentedViewController] != nil)
        {
            if ([[rootVC presentedViewController] isKindOfClass:UINavigationController.self]) {
                UINavigationController *navigationController = (UINavigationController *)[rootVC presentedViewController];
                return [[navigationController viewControllers] lastObject];
            }
            return [self getVisibleViewController : [rootVC presentedViewController]];
        }
        return nil;
    }