在一般应用中,我们使用 addSubview
方法是添加到当前控制器 ViewController
上的,但是对于某些情况下,我们需要把视图添加到顶层控制器视图上,即要获取顶层视图控制器。
- 当前顶层窗口
//UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
UIWindow *window = [UIApplication sharedApplication].keyWindow;
// 添加到窗口
[window addSubview:testView];
- 获取View父视图
- (UIViewController )viewController
{
for (UIView next = [self superview]; next; next = next.superview) {
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
- 获取最上层控制器|当前控制器
//获取当前最上层的控制器
-(UIViewController *) getTopOrCurrentViewController
{
UIWindow *topWindow = [UIApplication sharedApplication].keyWindow;
if (topWindow.windowLevel != UIWindowLevelNormal)
{
topWindow = [self returnWindowWithWindowLevelNormal];
}
UIViewController *topController = topWindow.rootViewController;
if(topController == nil)
{
topWindow = [UIApplication sharedApplication].delegate.window;
if (topWindow.windowLevel != UIWindowLevelNormal)
{
topWindow = [self returnWindowWithWindowLevelNormal];
}
topController = topWindow.rootViewController;
}
while(topController.presentedViewController)
{
topController = topController.presentedViewController;
}
if([topController isKindOfClass:[UINavigationController class]])
{
UINavigationController *nav = (UINavigationController*)topController;
topController = [nav.viewControllers lastObject];
while(topController.presentedViewController)
{
topController = topController.presentedViewController;
}
}
return topController;
}
-(UIWindow *) returnWindowWithWindowLevelNormal
{
NSArray *windows = [UIApplication sharedApplication].windows;
for(UIWindow *topWindow in windows)
{
if (topWindow.windowLevel == UIWindowLevelNormal)
return topWindow;
}
return [UIApplication sharedApplication].keyWindow;
}