本文介绍了在iOS中查找rootViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ShareKit中,代码需要确定rootViewController的位置,以便显示模态视图。出于某种原因,代码在iOS 5中失败:
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].");
这是在击中断言。
简单地使用以下代码有什么问题呢?
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?
推荐答案
我不确定你是否可以依赖窗口。 rootViewController
b / c你不必设置它。您只需将子视图添加到窗口即可。以下似乎工作正常:
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];
这篇关于在iOS中查找rootViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!