UINavigationController
中有visibleViewController
和topViewController
-
visibleViewController
当前显示的控制器 -
topViewController
是某个导航栈的栈顶视图 -
visibleViewController
跟导航栈没有关系,只是当前显示的控制器,也就是说任意一个导航的visibleViewController
所返回的值应该是一样的, - topViewController 是某个导航栈的栈顶视图,和导航控制器相关
换句话说如果在仅有一个导航栈上,visibleViewController
和topViewController
应该是没有区别得。
方法一 : 获取当前显示的控制器 UIWindow (Visible)
- (UIViewController *)visibleViewController {
UIViewController *rootViewController =[[[[UIApplication sharedApplication] 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:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else {
return rootViewController;
}
}
值得注意的是
[[[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