在iOS中查找rootViewController

Jim*_*Jim 10 uiapplication ios

在ShareKit中,代码需要确定rootViewController的位置,以便它可以显示模态视图.出于某种原因,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].");
Run Code Online (Sandbox Code Playgroud)

这是在打断断言.

简单地使用以下代码有什么问题呢?

rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常.它会在某些条件下失败吗?

XJo*_*nes 28

我不确定你是否可以依靠window.rootViewControllerb/c而不必设置它.您只需将子视图添加到窗口即可.以下似乎工作正常:

id rootVC = [[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0] nextResponder];
Run Code Online (Sandbox Code Playgroud)