zoukankan      html  css  js  c++  java
  • iOS 根据类名,获取已存在的controller,无论是模态出来还是push出来的controller,都可以找到

    我们在写代码时,有时会遇到:需要知道某个controller是否已经存在,或着,要拿到已存在的某个controller对象,这里提供一种可以获取到你想要的controller对象,只需要传入类名即可,废话不多说直接上代码:

    - (UIViewController *)getActivityViewController:(NSString *)controllerName {
        UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topVC.presentedViewController) {
            topVC = topVC.presentedViewController;
            if ([[topVC.class description] isEqualToString:@"UINavigationController"]) {
                UINavigationController *navi = (UINavigationController *)topVC;
                if (navi && navi.viewControllers && navi.viewControllers.count > 0) {
                    NSInteger count = navi.viewControllers.count;
                    for (NSInteger i=count-1; i>=0; i--) {
                        UIViewController *controller = [navi.viewControllers objectAtIndex:i];
                        if ([[controller.class description] isEqualToString:controllerName]) {
                            return controller;
                        }
                    }
                }
            }
        }
        return nil;
    }

    如果当前存在的同一类名的controller有多个,你要拿到最新的一个可以用下面这种方法:

    - (UIViewController *)getActivityViewController:(NSString *)controllerName {
        UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *resaultVC = nil;
        while (topVC.presentedViewController) {
            topVC = topVC.presentedViewController;
            if ([[topVC.class description] isEqualToString:@"UINavigationController"]) {
                UINavigationController *navi = (UINavigationController *)topVC;
                if (navi && navi.viewControllers && navi.viewControllers.count > 0) {
                    NSInteger count = navi.viewControllers.count;
                    for (NSInteger i=count-1; i>=0; i--) {
                        UIViewController *controller = [navi.viewControllers objectAtIndex:i];
                        if ([[controller.class description] isEqualToString:controllerName]) {
                            resaultVC =  controller;
                        }
                    }
                }
            }
        }
        return resaultVC;
    }

    当然这两个方法的前提是,你如果是 present 出来的congtroller,并且导航控制器是 UINavigationController 类型,如果导航控制器是自定义的,那么在判断 if ([[topVC.class description] isEqualToString:@"UINavigationController"]) 时@"UINavigationController" 要替换成你自定义的类名即可。 

  • 相关阅读:
    deepin 安装版本管理工具
    deepin 安装maven
    deepin 安装 idea
    启动VMware环境下的Linux操作系统,添加新分区
    Centos6.*安装vsftpd
    easyui-datebox 年月视图显示
    oracle-数据库泵EXPDP导出用户下所有
    Oracle虚拟机配置
    JSON理解
    Python语法基础_04.元组、函数-上
  • 原文地址:https://www.cnblogs.com/shisishao/p/5799367.html
Copyright © 2011-2022 走看看