Find the current top view controller 发表于 2015-12-10 | 分类于 iOS | Objective-C version 12345678910111213141516171819202122- (UIViewController *)topViewController{ return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController];}- (UIViewController *)topViewController:(UIViewController *)rootViewController{ if (rootViewController.presentedViewController == nil) { UINavigationController *navigationController = (UINavigationController *)rootViewController; return [[navigationController viewControllers] lastObject]; } if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) { UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController; UIViewController *lastViewController = [[navigationController viewControllers] lastObject]; return [self topViewController:lastViewController]; } UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController; return [self topViewController:presentedViewController];} Swift version 1234567891011121314151617181920212223242526272829func visibleViewController() -> UIViewController? { if let rootViewController: UIViewController = self.rootViewController { return UIWindow.getVisibleViewControllerFrom(rootViewController) }return nil}class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController { if vc.isKindOfClass(UINavigationController.self) { let navigationController = vc as UINavigationController return UIWindow.getVisibleViewControllerFrom( navigationController.visibleViewController) } else if vc.isKindOfClass(UITabBarController.self) { let tabBarController = vc as UITabBarController return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!) } else { if let presentedViewController = vc.presentedViewController { return UIWindow.getVisibleViewControllerFrom(presentedViewController.presentedViewController!) } else { return vc; }}