iOS 获取当前显示的ViewController

我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或需要 presentViewController,或pushViewContrller,这些操作都需要获取当前正在显示的ViewController。

发觉百度搜出来好多不科学的方法,有时候还是自己动脑子想好。。。
下面提供了一个公用的方法去获取当前ViewController,也建议直接改成静态方法,放到工具类里直接调用更加科学。

具体代码如下:

//获取当前屏幕显示的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;
}

解析:代码主要使用了递归的思想(哈哈哈,毕业工作半年,发觉第一次写iOS用到递归,突然觉得高大上)。
[UIApplication sharedApplication].keyWindow.rootViewController获取到的是项目的根视图,结合可能用到UITabBarController或者UINavigationController作为导航结构,以及可能present出新的VC,其实如果用storyboard的方式写UI的话就很清晰,类似树的结构,再利用递归找到当前视图。

ps:
如果是需要push新的视图,就很简单啦:
用上面的方法获取到顶层的视图,判断currentVC.navigationController是否为nil。(为nil,则新建UINavigationController在push;否则直接用currentVC.navigationController去push)

ps2:
补充评论里好的建议,如果用到的场景主要是vc里,可以弄成类别如下:

#import "UIViewController+Helper.h"

@property (nonatomic, strong ,readonly) UIViewController * _Nullable currentVC;

//当前屏幕显示的viewcontroller
-(UIViewController *)currentVC{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *controller = [self getCurrentVCFrom:rootViewController];
return controller;
}

//getCurrentVCFrom参考上文

还有什么不懂的就留言问问哈。。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言:我们在VC中添加一个自定义的View时,有时候添加的这个View上,可能会有按钮或者其他的点击事件,如果该事...
    辰星撒欢的蒜苗阅读 1,040评论 2 2
  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 2,586评论 1 14
  • 前言的前言 唐巧前辈在微信公众号「iOSDevTips」以及其博客上推送了我的文章后,我的 Github 各项指标...
    VincentHK阅读 5,467评论 3 44
  • 天机老人有一弟子,名叫八锦,颇有术学天赋。天机术成之后,八锦游历人间,于黎国遇黎国主,黎国主深知其具经天纬地之才,...
    锦玄飞墨阅读 440评论 0 1
  • 1、 最近天气越来越热,趁着午后略微凉爽的时候,断断续续的把夏天的衣服理了一遍。 清理的过程中,我惊讶的发现,好像...
    大脸and小脸阅读 515评论 0 1