Finding the rootViewController in iOS

喜欢而已 提交于 2020-01-01 04:37:27

问题


In ShareKit, the code needs to determine where the rootViewController is so it can show a modal view. For some reason, the code is failing in iOS 5:

    // Try to find the root view controller programmically

    // Find the top window (that is not an alert view or other window)
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    if (topWindow.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(topWindow in windows)
        {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                break;
        }
    }

    UIView *rootView = [[topWindow subviews] objectAtIndex:0];  
    id nextResponder = [rootView nextResponder];

    if ([nextResponder isKindOfClass:[UIViewController class]])
        self.rootViewController = nextResponder;

    else
        NSAssert(NO, @"ShareKit: Could not find a root view controller.  You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");

This is hitting the assert.

What is wrong with simply using the following code, instead?

rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];

This seems to be working fine. Will it fail under some conditions?


回答1:


I'm not sure if you can rely on window.rootViewController b/c you don't have to set it. You can just add a subview to the window. The following seemed to work fine:

id rootVC = [[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0] nextResponder];



回答2:


Swift way to do it, you can call this from anywhere:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
public var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }

    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

Its included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions




回答3:


This worked for me:

UIViewController * rootViewController = (UIViewController *)[[[UIApplication.sharedApplication.keyWindow subviews] firstObject];


来源:https://stackoverflow.com/questions/8585881/finding-the-rootviewcontroller-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!