ios - 在 iOS 中查找 rootViewController

标签 ios uiapplication

在 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].");

这是命中断言。

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

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

这似乎工作正常。它会在某些情况下失败吗?

最佳答案

我不确定你是否可以依赖 window.rootViewController b/c 你不必设置它。您可以只向窗口添加一个 subview 。以下似乎工作正常:

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

关于ios - 在 iOS 中查找 rootViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8585881/

相关文章:

ios - 使 UISlider 高度变大?

objective-c - 如何从另一个 View Controller 呈现一个 View Controller

ios - SwiftUI 中的 ForEach 在部分之间交换 View (从而重新使用它们),而不是更新数据并尊重 View 修饰符

ios - 如何在 iOS 中显示当前和前 6 个月的年份?

objective-c - UIDeviceOrientationDidChangeNotification 与 UIApplicationDidChangeStatusBarOrientationNotification

ios - 用户强行终止应用程序 : Registering this event

ios - UIApplication 的委托(delegate)属性

ios - WatchConnectivity 共享 key

ios - 什么是 UserNotification 框架相当于 didReceive 通知 : UILocalNotification?

ios - 一旦 UIApplication.SharedApplication.OpenUrl 加载了 Web 链接,MonoTouch 会发出通知