iOS 获得屏幕正在显示的Controller(自定义的控制器)的实用方法

来源:互联网 发布:java配置文件 编辑:程序博客网 时间:2024/05/22 12:19

项目有点紧张,好久没有写点东西了。后面我会抽更多时间学习和分享学习的一些总结,分享给各位,请持续关注。


具体场景我都不说了。直接上代码

- (void)needShowLogin{    YPJGLoginViewController * login = [[YPJGLoginViewController alloc] init];    login.hidesBottomBarWhenPushed = YES;    UIViewController * VC = [self currentViewController];    YPJGLog(@"当前显示的控制器%@",VC);    //判断是否已经显示登录窗口,没有显示则push显示    if (![[NSString stringWithUTF8String:object_getClassName(VC)] isEqual:[NSString stringWithUTF8String:object_getClassName(login)]])    {        [VC.navigationController pushViewController:login animated:YES];    }}//获取Window当前显示的ViewController- (UIViewController*)currentViewController{    //获得当前活动窗口的根视图    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;    while (1)    {        //根据不同的页面切换方式,逐步取得最上层的viewController        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;}



网上还有另外一种方法 (经测试只拿到当前 活活动窗口的根视图 不推荐)

- (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;}


顺便分享一个 字符串为空判断的宏定义 很高效


#define IsNOTNullOrEmptyOfNSString(string) !((![string isKindOfClass:[NSString class]])||[string isEqualToString:@""] || (string == nil) || [string isEqualToString:@"<null>"]|| [string isEqualToString:@"(null)"]|| [string isEqualToString:@"null"]|| [string isEqualToString:@"nil"] || [string isKindOfClass:[NSNull class]]||[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)


本期暂时到这里,需要什么新的ios相关知识,也可以给我留言哦,我们一起学习研究



0 0