在开发的过程中,因为现实的问题,需要获取各种情况下的窗口或者是控制器,本文就简单介绍接种获取window和ViewController的方法:
获取window
1.获取控制器的keyWindow
通过UIApplication获取:(推荐,随时都可以获取到window)
UIWindow *window = [UIApplication sharedApplication].keyWindow;
值得注意的是,这时候获取到的window不一定是屏幕最前面的window,因为像UIAlert和键盘等,都是在屏幕最前面的window,或者是modal出来的控制器。这时候需要获取最前面的窗口,不然就可能显示出问题。
2.获取顶层window
UIWindow window = [[UIApplication sharedApplication].windows lastObject];
[window addSubview:aView];// 将要显示的view添加到窗口
获取当前正在显示的ViewController
1.我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或用当前view presentViewController,或pushViewContrller,这些操作都需要获取当前正在显示的ViewController。
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
UIViewController *result = nil;
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows)
{
if (tmpWin.windowLevel == UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
UIView *frontView = [[window subviews] objectAtIndex:0];
id nextResponder = [frontView nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
result = nextResponder;
else
result = window.rootViewController;
return result;
}
2.获取当前屏幕中present出来的view controller。
- (UIViewController *)getViewController
{
UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *topVC = appRootVC;
if (topVC.presentedViewController) {
topVC = topVC.presentedViewController;
}
return topVC;
}