在iOS中查找rootViewController
在 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];
这似乎运作良好。在某些条件下会失败吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定您是否可以依赖
window.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:快速的方法,您可以从任何地方调用它:
它作为标准函数包含在:
https://github。 com/goktugyil/EZSwiftExtensions
Swift way to do it, you can call this from anywhere:
Its included as a standard function in:
https://github.com/goktugyil/EZSwiftExtensions
这对我有用:
This worked for me: