在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]; 

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

我不知道,如果你可以依靠window.rootViewController B / C你不必设置它。 你可以在窗口中添加一个子视图。 以下似乎工作正常:

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

迅速做到这一点,你可以从任何地方调用这个:

 /// 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 } 

它作为标准function包含在:

https://github.com/goktugyil/EZSwiftExtensions