//获取当前控制器
+ (UIViewController*)currentViewController {
return [self currentViewControllerWithRootViewController:[self getKeyWindow].rootViewController];
}
//获取KeyWindow
+ (UIWindow *)getKeyWindow {
if (@available(iOS 13.0, *)) {
for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
if (windowScene.activationState == UISceneActivationStateForegroundActive) {
for (UIWindow *window in windowScene.windows) {
if (window.isKeyWindow) {
return window;
break;
}
}
}
}
}
else {
return [UIApplication sharedApplication].keyWindow;
}
return nil;
}
+ (UIViewController*)currentViewControllerWithRootViewController:(UIViewController*)rootViewController {
if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self currentViewControllerWithRootViewController:presentedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self currentViewControllerWithRootViewController:navigationController.visibleViewController];
} else if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabBarController = (UITabBarController *)rootViewController;
return [self currentViewControllerWithRootViewController:tabBarController.selectedViewController];
} else {
return rootViewController;
}
}
获取当前
//获取手机当前显示的ViewController
-(UIViewController*)currentViewController{
UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
while (1) {
if ([vc isKindOfClass:[UITabBarController class]]) {
vc = ((UITabBarController*)vc).selectedViewController;
}
if ([vc isKindOfClass:[UINavigationController class]]) {
vc = ((UINavigationController*)vc).visibleViewController;
}
if (vc.presentedViewController) {
vc = vc.presentedViewController;
}else{
break;
}
}
return vc;
}