获取程序最上层UIViewController
作者:
tp夕阳武士 | 来源:发表于
2019-10-22 14:20 被阅读0次1.如何获取应用topviewcontroller?
static UIViewController *get_top_view_controller() {
UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;
while ( [vc isKindOfClass:[UINavigationController class]] ||
[vc isKindOfClass:[UITabBarController class]] ||
vc.presentedViewController ) {
if ( [vc isKindOfClass:[UINavigationController class]] )
vc = [(UINavigationController *)vc topViewController];
if ( [vc isKindOfClass:[UITabBarController class]] )
vc = [(UITabBarController *)vc selectedViewController];
if ( vc.presentedViewController )
vc = vc.presentedViewController;
}
return vc;
}
//上面这个方法,如果要对外暴露成OC方法接口应该改成下面写法:
+( UIViewController *)get_top_view_controller() {
UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;
while ( [vc isKindOfClass:[UINavigationController class]] ||
[vc isKindOfClass:[UITabBarController class]] ||
vc.presentedViewController ) {
if ( [vc isKindOfClass:[UINavigationController class]] )
vc = [(UINavigationController *)vc topViewController];
if ( [vc isKindOfClass:[UITabBarController class]] )
vc = [(UITabBarController *)vc selectedViewController];
if ( vc.presentedViewController )
vc = vc.presentedViewController;
}
return vc;
}
//思路:
//1.获取应用当前rootViewController(根视图),注意:根视图是程序的最底层视图控制器层
//2.存在可能性: UINavigationController/UITabBarController/UIViewController
//3.只要当上面最后获得的VC.presentedViewController == nil
//才能说明当前的控制器是最顶层的
本文标题:获取程序最上层UIViewController
本文链接:https://www.haomeiwen.com/subject/tntqvctx.html
网友评论