一、UINavigationController 中有visibleViewController和topViewController
1. visibleViewController 就是当前显示的控制器
2. topViewController 是某个导航栈的栈顶视图
3. visibleViewController和哪个导航栈没有关系,只是当前显示的控制器,也就是说任意一个导航的visibleViewController所返回的值应该是一样的,
但是topViewController 就是某个导航栈的栈顶视图,和导航息息相关
换句话说如果在仅有一个导航栈上,visibleViewController和topViewController应该是没有区别得。
二、获取当前显示的控制器 UIWindow (Visible)
- (UIViewController *)visibleViewController {
UIViewController *rootViewController =[[[[UIApplicationsharedApplication] delegate] window] rootViewController];
return [UIWindow getVisibleViewControllerFrom:rootViewController];
}
方法一
+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [UIWindow getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [UIWindow getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
} else {
if (vc.presentedViewController) {
return [UIWindow getVisibleViewControllerFrom:vc.presentedViewController];
} else {
return vc;
}
}
}
方法二
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
if ([rootViewController isKindOfClass:[UITabBarControllerclass]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
值得注意的是
1、[[[UIApplication sharedApplication] keyWindow]rootViewController] 有时为nil 比如当页面有菊花在转的时候,这个rootViewController就为nil;所以使用[[[[UIApplication sharedApplication] delegate] window] rootViewController] 或者
[[[[UIApplication sharedApplication] windows] objectAtIndex:0]rootViewController]
presentedViewController 和 presentingViewController
当A弹出B
A.presentedViewController=B
B.presentingViewController=A