iOS --- 获取屏幕顶层的UIViewController

经常会遇到一些场景, 要通过代码获取到当前显示在屏幕最顶层的UIViewController. 如何获取呢?

获取rootViewController

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller’s view as the content view of the window. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.

rootViewController的设定通常会在设置keyWindow的时候遇到, 表示该UIWindow的最底层的UIViewController.

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

获取currentViewController

一般情况下, 可通过如下方式获取当前屏幕最顶层的ViewController:

- (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;

        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 更好的阅读体验,请到个人博客阅读: iOS中的系统转场 请忽略标题,😂,本文记录的是对下图所示的Kind, Pre...
    CaryaLiu阅读 7,124评论 0 1
  • 我推荐的第一本书叫西游记,大家都知道这本书是四大名著之一,是很著名的一本书啊。我之所以推荐这本书,是有原因的,下面...
    311635a8c051阅读 2,910评论 0 0
  • 慵懒的午后,一个人躺在沙发上毫无睡意,打开手机,立马呈现出一条微信,送给你亲爱的朋友《漂洋过海来看你》。熟悉的旋律...
    花开好时节阅读 2,312评论 1 1