首页 > 代码库 > iOS 获取当前界面所在的视图控制器
iOS 获取当前界面所在的视图控制器
当前界面所在的视图控制器 逐步完善的过程
一、
//获取当前屏幕显示的viewcontroller (这里面获取的相当于rootViewController) - (UIViewController *)getCurrentVC { UIViewController *result = nil; UIWindow * window = [[UIApplication sharedApplication] keyWindow]; if (window.windowLevel != UIWindowLevelNormal) { NSArray *windows = [[UIApplication sharedApplication] windows]; for(UIWindow * tmpWin in windows) { if (tmpWin.windowLevel == UIWindowLevelNormal) { window = tmpWin; break; } } } UIView *frontView = [[window subviews] objectAtIndex:0]; id nextResponder = [frontView nextResponder]; if ([nextResponder isKindOfClass:[UIViewController class]]) result = nextResponder; else result = window.rootViewController; return result; }
二、不够完善
//获取到当前所在的视图 + (UIViewController *)presentingVC{ UIWindow * window = [[UIApplication sharedApplication] keyWindow]; if (window.windowLevel != UIWindowLevelNormal){ NSArray *windows = [[UIApplication sharedApplication] windows]; for(UIWindow * tmpWin in windows){ if (tmpWin.windowLevel == UIWindowLevelNormal){ window = tmpWin; break; } } } UIViewController *result = window.rootViewController; while (result.presentedViewController) { result = result.presentedViewController; } if ([result isKindOfClass:[MYTabBarViewController class]]) { result = [(MYTabBarViewController *)result selectedViewController]; } if ([result isKindOfClass:[UINavigationController class]]) { result = [(UINavigationController *)result topViewController]; } return result; }
三、参数传入导航试图控制器或者UITabBarController self.window.rootViewController 也可。(这个比较通用)
+ (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; } }
当然也可以根据自己项目的框架和业务逻辑 自己写相应的方法!
iOS 获取当前界面所在的视图控制器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。