我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或用当前view presentViewController,或pushViewContrller,这些操作都需要获取当前正在显示的ViewController。
一般我用
UIViewController * vcCurrent =[[UIApplication sharedApplication] keyWindow].currentViewController;就可以了,但是在网上看到了下面这种方法,应该是比上面更严谨些,但是现在还没遇到展现她的特别作用的时候,不过也贴出来,说不定以后会用到。
- //获取当前屏幕显示的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;
- }
if ([vcCurrent isKindOfClass:[UITabBarController class]]) {
UITabBarController * vcTabBar = (UITabBarController *)vcCurrent;
NSArray * arrVCS = [vcTabBar viewControllers];
FMNavigationController * vcNav = [arrVCS objectAtIndex:vcTabBar.selectedIndex];
[vcNav pushViewController:vcNext animated:YES];
}else{
[vcCurrent.navigationController pushViewController:vcNext animated:YES];
}