欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 获取当前屏幕显示的viewcontroller

程序员文章站 2024-01-15 08:15:40
...

//获取当前屏幕显示的viewcontroller

  • (UIViewController *)getCurrentVC

{

UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;



UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];



return currentVC;

}

  • (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC

{

UIViewController *currentVC;



if ([rootVC presentedViewController]) {

    // 视图是被presented出来的

    

    rootVC = [rootVC presentedViewController];

}



if ([rootVC isKindOfClass:[UITabBarController class]]) {

    // 根视图为UITabBarController

    

    currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];

    

} else if ([rootVC isKindOfClass:[UINavigationController class]]){

    // 根视图为UINavigationController

    

    currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];

    

} else {

    // 根视图为非导航类

    

    currentVC = rootVC;

}



return currentVC;

}