首先看下苹果的官方文档
topViewController
The view controller at the top of the navigation stack. (read-only)
visibleViewController
The view controller associated with the currently visible view in the navigation interface. (read-only)
Discussion
The currently visible view can belong either to the view controller at the top of the navigation stack or to a view controller that was presented modally on top of the navigation controller itself.
这里我们可以看出, 如果都只是用navigation push和pop的话, topViewController和visiableViewController没有区别的, 都指的是我们navigation push出来的最后一个控制器, 只有在用navigation模态的时候, 我们的navigation会记录下这个被模态出来的控制器, 这时的topViewController和visiableViewController不一样, 这时的visiableViewController是被模态出来的那个控制器, 而topViewController则是最后一个被push出来的控制器. 从上面的注释中我们可以看出topViewController指的就是我们的navigation当前堆栈控制器的最后一个, 而visiableViewController就没有这个限制, 在Discussion中很明确的指出, 指的是当前navigation中可见View的视图控制器或者是被当前navigation模态出来的控制器.
下面是获取当前的视图控制器, 是摘抄的网上的.可以参考下
获取当前显示的控制器 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 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;
}
}