前言
在项目中经常需要获取当前顶层控制器,然后去完成某些操作。这里记录下我的实现方式。
代码实现
方式一
+ (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;
}
}
方式二
- (UIViewController *)topController {
UIViewController *viewController = self;
while (1) {
if (self.presentedViewController) {
viewController = self.presentedViewController;
} else if ([self isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController* )viewController;
viewController = [navigationController.childViewControllers lastObject];
} else if ([viewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController* )viewController;
viewController = tabBarController.selectedViewController;
} else {
NSUInteger childViewControllerCount = viewController.childViewControllers.count;
if (childViewControllerCount > 0) {
viewController = viewController.childViewControllers.lastObject;
return viewController;
} else {
return viewController;
}
}
}
return viewController;
}