如何在IOS上找到最顶层视图控制器现在,我遇到了一些情况,可以方便地找到“最顶层”视图控制器(负责当前视图的视图控制器),但还没有找到方法。从根本上说,挑战是这样的:考虑到这一点在非视图控制器的类中执行(或视图)[并且没有活动视图的地址]并且没有传递最顶层视图控制器的地址(或者说导航控制器的地址),是否有可能找到该视图控制器?(如果是的话,怎么做?)或者,如果做不到这一点,是否有可能找到最上面的视图?
3 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
[UIApplication sharedApplication].keyWindow.rootViewController;
呼唤远方
TA贡献1856条经验 获得超11个赞
+ (UIViewController*) topMostController{ UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController; while (topController.presentedViewController) { topController = topController.presentedViewController; } return topController;}
SWIFT 3.0+
func topMostController() -> UIViewController? { guard let window = UIApplication.shared.keyWindow, let rootViewController = window.rootViewController else { return nil } var topController = rootViewController while let newTopController = topController.presentedViewController { topController = newTopController } return topController}
临摹微笑
TA贡献1982条经验 获得超2个赞
- (UIViewController*)topViewController { return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.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; }}
- 3 回答
- 0 关注
- 1222 浏览
添加回答
举报
0/150
提交
取消